Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Handling File Uploads in Django

1. Introduction

File uploads are a common feature in web applications. In Django, handling file uploads involves defining a form, updating the settings, and writing views and templates to handle the files. By the end of this tutorial, you will have a clear understanding of how to handle file uploads in Django.

2. Setting Up

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

pip install django

Create a new Django project and an app within that project:

django-admin startproject myproject
cd myproject
python manage.py startapp myapp

3. Configuring Settings

Update your settings.py to handle media files. Add the following configurations:

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

Ensure you have django.core.files.storage.FileSystemStorage included in your installed apps if you plan to use the default file storage system.

4. Creating the Model

Create a model to store the uploaded files. Open myapp/models.py and add the following code:

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 migrations to create the model in the database:

python manage.py makemigrations
python manage.py migrate

5. Creating the Form

Create a form to handle file uploads. Open myapp/forms.py and add the following code:

from django import forms
from .models import Document

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

6. Creating the View

Create a view to handle the form submission and file saving. Open myapp/views.py and add the following code:

from django.shortcuts import render, redirect
from django.core.files.storage import FileSystemStorage
from .models import Document
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('file_upload')
    else:
        form = DocumentForm()
    return render(request, 'upload.html', {'form': form})

7. Creating the Template

Create a template to display the form. Create a file named upload.html in myapp/templates/ and add the following code:

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

8. Configuring URLs

Update your URLs to include the file upload view. Open myproject/urls.py and add the following code:

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('upload/', views.upload_file, name='file_upload'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

9. Testing the File Upload

Run the Django development server to test the file upload functionality:

python manage.py runserver

Navigate to http://127.0.0.1:8000/upload/ in your web browser. You should see the file upload form. Try uploading a file and ensure it is saved in the media/documents/ directory.

10. Conclusion

In this tutorial, we covered the steps to handle file uploads in Django. We configured the settings, created a model, form, view, and template to manage file uploads. This should provide you with a solid foundation for handling file uploads in your Django projects.