Media files - Settings
Series: Static and media files
Today is turn of media file settings and dealing with file uploads in general. First, the settings required for development are as follows:
MEDIA_URL = 'media/'
MEDIA_ROOT = BASE_DIR / 'media_root'
MEDIA_URL
defines the public facing url for where media files are served from.
MEDIA_ROOT
defines where uploaded files are stored within the context of the project, for local development a folder in the project is an excellent start.
Finally when it comes to uploading files there are a few things to note.
- Using a FileField or ImageField are default ways to save files into a model.
- If your using a Django Form, then be sure to pass in
request.FILES
as well asrequest.POST
when instaniating the form - When constructing the HTML form in a template be sure to mark the
enctype
as"multipart/form-data"
. See the example below.
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<input type="submit" value="Upload File" />
</form>
Tomorrow we will look at static files and media files when deploying a Django project.