Where to store user uploaded files in Django
I'm building a Django app where users will upload a CSV file. Each row in the CSV file will then be added to the DB (after validating the data). The file can then be discarded.
From the Django documentation, I'm using this to save the file.
def handle_uploaded_file(f):
with open('some/file/name.txt', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
There's a lot of warnings on the Django site about handling user uploaded files so my question is, where should these files be saved? My guess is it doesn't matter, but I want to be sure.
At the moment I plan to create a variable called UPLOADS_URL in my settings file. All uploaded files will then be stored in there.
Indeed it does not matter so much where you put these files, especially if you discard them after. The only important thing is to put them in a place that is not accessible by your webserver. So for example if your static files and/or your app code is stored in the /var/www
directory, do NOT put the uploaded files there.
There are existing Django settings called MEDIA_ROOT
and MEDIA_URL
that are used as the default place to store the uploaded files. MEDIA_ROOT
is the path where the files are stored, MEDIA_URL
is the URL path that a http client may use to retrieve the uploaded files (so in your case it is not needed).
What you need to be really careful about is the content of the CSV files. As you are going to store them in DB and re-use them later, you should validate carefully the content before storing it. For example, if you are storing a string that you will later display on the site, you want to make sure it doesn't contain any javascript...