why Django upload a file to server failed

24 views Asked by At
if request.method == 'POST': 
    k = request.FILES
    obj = request.FILES['upload']
    t = int(time.time())
    jobid = 'jobid'+str(t)
    job_name = jobid + '_' + obj.name
    print(job_name)
    fr = open('prediction/PanPep/upload/' + job_name, 'wb+')

i used request.FILES to get a uploaded file and create this file on my server. It was fine when I uploaded the first file. But then i get an error when you i to create the file.

this is error: FileNotFoundError: [Errno 2] No such file or directory: 'prediction/PanPep/upload/jobid1709638360_Example_zero-shot.csv' [05/Mar/2024 19:32:40] "POST /panpep/ HTTP/1.1" 500 67598

It seems to be due to some kind of conflict,how to explian this phenomenon and how i fix it.

Thanks in advance!

1

There are 1 answers

1
Mohamed ElKalioby On

In Web, it is not perferable to use relative paths as you don't know what is the current directory, so it is always better to use Absolute paths, In Django you can achieve that by using BASE_DIR.

Also, for production purposes, it is better to put this path in the settings .py

UPLOADS_DIR = BASE_DIR + 'prediction/PanPep/upload/'

Then in your code,

from django.conf import settings
fr = open(settings.UPLOADS_DIR + job_name, 'wb+')

You can check this answer for more details.