Changes to Make to the Settings.py File for File Uploads in Django 


               


Changes to Make to the Settings.py File for File Uploads in Django



Python


In this article, we show what changes need to be made to the settings.py file for file uploads in Django.

So, basically, by convention, in Django, when you are configuring your website to handle file uploads, you want files to uploaded to the media directory.

Even though you create a static directory for things such as images, videos, and other static files, when you are handling file uploads, Django wants these uploaded files to be in a separate directory from the static directory, and this directory is the media directory.

One reason Django wants files to be uploaded to a separate directory is because these files are third-party content, which could be a security risk. For reasons such as these, Django wants a separate media directory for uploaded files.

So, you have a create a media directory in the root directory of your website and make changes to various places in your project, including the settings.py File.

In this article, we'll go over what needs to be added to the settings.py file and why.

So, let's just get directly into it.

So, since we're creating another directory, media, we have specify the path to this media directory, so that Django knows where it is. This is more for the server.

So, the following must be added to the settings.py File.



So, since we're creating another directory, media, we have specify the path to this media directory, so that Django knows where this folder is located.

And MEDIA_URL is for scripts or various files in templates, so that when we reference MEDIA_URL, the script knows the path, where to go.

Besides these 2 lines, there's one other line we should add to the settings.py File and this in TEMPLATES set in the OPTIONS dictionary.

You want to add the following line to the OPTIONS dictionary, 'django.template.context_processors.media' What this does is it allows you to reference the MEDIA_URL variable in template directories.

So the OPTIONS dictionary should look like the following.



So, this concludes all the changes we need to do in the settings.py file for file uploads in Django.

Be aware that you have to add things to other files as well such as urls.py and so. We'll get to that in another tutorial. But just be aware that in order to do file uploads, you will need to create a media file in the root directory and then make the above changes to the settings.py file.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...