Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to File Uploads in Django

1. Overview

File uploads are a common feature in many web applications. This tutorial will guide you through the steps required to implement file uploads in a Django application. We will cover the necessary configurations, creating forms, handling file uploads in views, and displaying uploaded files.

2. Setting Up Your Django Project

First, ensure you have Django installed. If not, you can install it using the following command:

pip install django

Create a new Django project and app:

django-admin startproject fileupload_project
cd fileupload_project
django-admin startapp uploads

3. Configuring Models

Define a model in uploads/models.py to handle file uploads:

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)

Run the following commands to create the database tables for your model:

python manage.py makemigrations
python manage.py migrate

4. Creating Forms

Create a form in uploads/forms.py to handle the file upload:

from django import forms
from .models import Document

class DocumentForm(forms.ModelForm):
   class Meta:
      model = Document
      fields = ('description', 'document', )

5. Handling File Uploads in Views

Update your views in uploads/views.py to process the file upload:

from django.shortcuts import render, redirect
from .forms import DocumentForm

def upload_file(request):
   if request.method == 'POST':
      form = DocumentForm(request.POST, request.FILES)
      if form.is_valid():
         form.save()
         return redirect('upload_file')
   else:
      form = DocumentForm()
   return render(request, 'upload.html', {'form': form})

6. Creating Templates

Create a template uploads/templates/upload.html to render the form:

<!DOCTYPE html>
<html>
<head>
   <title>File Upload</title>
</head>
<body>
   <h1>Upload a new document</h1>
   <form method="post" enctype="multipart/form-data">
      {% csrf_token %}
      {{ form.as_p }}
      <button type="submit">Upload</button>
   </form>
</body>
</html>

7. Configuring URLs

Update your uploads/urls.py to include the upload view:

from django.urls import path
from . import views

urlpatterns = [
   path('', views.upload_file, name='upload_file'),
]

Include the uploads URLs in your project’s fileupload_project/urls.py:

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
   path('admin/', admin.site.urls),
   path('uploads/', include('uploads.urls')),
]

8. Handling Media Files

To serve media files during development, ensure you add these settings in fileupload_project/settings.py:

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Update your fileupload_project/urls.py to serve media files:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

9. Running the Server

Run the development server to test the file upload functionality:

python manage.py runserver

Navigate to http://127.0.0.1:8000/uploads/ to see the file upload form. You should be able to upload files and see them saved in the media/documents/ directory.

10. Conclusion

You've successfully implemented file uploads in a Django application! This tutorial covered the basics of setting up models, forms, views, and templates to handle file uploads. You can now expand this knowledge to handle more complex scenarios such as multiple file uploads, file validation, and more.