Django is a popular web framework that provides built-in support for handling file uploads and downloads. In this blog post, we will discuss how to upload and download files in Django using the built-in file handling capabilities.
Uploading Files in Django
Creating a Model for Storing Files
The first step to allowing users to upload files in your Django web application is to define a model for storing the uploaded files. We will use the built-in FileField
field to store the file content, and we will also add a CharField
field to provide a description of the file.
from django.db import models class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True)
In this model, we have defined a CharField
for the file description, a FileField
for the file content, and a DateTimeField
to store the time the file was uploaded.
Building a Form for File Uploads
Next, we will create a form that allows users to upload files. We will use the built-in ModelForm
class and specify the Document
model as the form’s model.
from django import forms from .models import Document class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('description', 'document')
In this form, we have included fields for the description
and document
fields of the Document
model.
Now, we need to create a view that handles the file upload. We will use the built-in CreateView
class and specify the Document
model as the view’s model. We will also specify the DocumentForm
as the form to use for handling the upload.
from django.urls import reverse_lazy from django.views.generic.edit import CreateView from .models import Document from .forms import DocumentForm class DocumentCreateView(CreateView): model = Document form_class = DocumentForm template_name = 'upload.html' success_url = reverse_lazy('home')
In this view, we have specified the Document
model as the model to use, the DocumentForm
as the form to use, and the upload.html
template to render the form. We have also specified the home
URL as the success URL, which will be redirected to after the form is submitted.
To create a link that allows users to upload a file, we can create a simple HTML template called upload.html
:
{% extends 'base.html' %} {% block content %} <h2>Upload a file</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> {% endblock %}
This template extends a base template and displays a form that allows users to upload a file. The enctype
attribute is set to multipart/form-data
, which is required for file uploads. The {{ form.as_p }}
tag renders the form fields as a series of paragraphs.
Downloading Files in Django
Retrieving Files from the Database
Now that we have covered how to upload files in Django, let’s move on to downloading files. We will create a view that retrieves the file content from the database and sends it back to the user as an HTTP response.
from django.http import HttpResponse from django.shortcuts import get_object_or_404 from .models import Document def download(request, document_id): document = get_object_or_404(Document, pk=document_id) response = HttpResponse(document.document, content_type='application/pdf') response['Content-Disposition'] = f'attachment; filename="{document.document.name}"' return response
Building a View for File Downloads
In this view, we retrieve the Document
object with the specified document_id
from the database using the get_object_or_404
function. We then create an HttpResponse
object and set the file content as the response content. The content_type
attribute is set to application/pdf
to indicate that this is a PDF file. Finally, we set the Content-Disposition
header to attachment
to indicate that the file should be downloaded rather than displayed in the browser.
To create a link that allows users to download a file, we can create a simple HTML template called documents.html
:
{% extends 'base.html' %} {% block content %} <h2>Documents</h2> <ul> {% for document in documents %} <li> {{ document.description }} - <a href="{% url 'download' document.id %}">Download</a> </li> {% empty %} <li>No documents found.</li> {% endfor %} </ul> {% endblock %}
This template extends a base template and displays a list of documents. For each document, we display the description and a link to download the file. The link URL is generated using the url
template tag and the download
view name, passing in the document ID as a parameter.
To display the list of documents, we need to create a view that retrieves all the documents from the database and renders the documents.html
template.
from django.views.generic import ListView from .models import Document class DocumentListView(ListView): model = Document template_name = 'documents.html' context_object_name = 'documents'
In this view, we use the built-in ListView
class and specify the Document
model as the view’s model. We also specify the documents.html
template to render the list of documents and the documents
context variable to be used in the template.
To access this view, we need to add a URL pattern to our application’s urls.py
file:
from django.urls import path from .views import DocumentCreateView, DocumentListView, download urlpatterns = [ path('', DocumentListView.as_view(), name='home'), path('upload/', DocumentCreateView.as_view(), name='upload'), path('download/<int:document_id>/', download, name='download'), ]
In this URL pattern, we specify the URL path for the download
view and include the document_id
parameter in the URL. We also include the name
parameter to provide a name for the URL pattern, which we can use in our templates to generate URLs.

Conclusion:
In this blog post, we have covered how to upload and download files in Django. We have shown how to define a model for storing uploaded files, how to create a form for handling file uploads, and how to create a view for handling file downloads. We have also shown how to generate URLs for uploading and downloading files in our templates using Django’s built-in URL handling capabilities. With this knowledge, you can create web applications that allow users to upload and download files in a secure and efficient manner