Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

File Upload Validation in Django

Introduction

File upload is a common feature in web applications. However, validating the uploaded files is crucial to ensure security and proper functioning of the application. In this tutorial, we will cover how to validate file uploads in a Django application, including checking file size, type, and more.

Setting Up Django Project

Before we dive into file upload validation, let's set up a basic Django project. Open your terminal and run the following command:

django-admin startproject fileupload

Navigate into the project directory:

cd fileupload

Create a new app named 'uploads':

python manage.py startapp uploads

Creating the File Upload Form

First, let's create a simple form to handle file uploads. In uploads/forms.py, add the following code:

from django import forms

class UploadFileForm(forms.Form):
    file = forms.FileField()
                

Validating File Size

We can add a custom validator to check the file size. Create a file named validators.py in the uploads directory and add the following code:

import os
from django.core.exceptions import ValidationError

def validate_file_size(file):
    max_size_kb = 5120
    if file.size > max_size_kb * 1024:
        raise ValidationError(f"File size cannot exceed {max_size_kb}KB.")
                

Now, use this validator in the form field. Update forms.py as follows:

from django import forms
from .validators import validate_file_size

class UploadFileForm(forms.Form):
    file = forms.FileField(validators=[validate_file_size])
                

Validating File Type

To ensure that only specific file types can be uploaded, we can add another validator. Update validators.py:

def validate_file_extension(file):
    ext = os.path.splitext(file.name)[1]
    valid_extensions = ['.jpg', '.jpeg', '.png', '.gif']
    if not ext.lower() in valid_extensions:
        raise ValidationError("Unsupported file extension.")
                

Include this validator in the form field as well:

from .validators import validate_file_size, validate_file_extension

class UploadFileForm(forms.Form):
    file = forms.FileField(validators=[validate_file_size, validate_file_extension])
                

Handling the File Upload in Views

Next, let's handle the file upload in a view. In uploads/views.py, add the following code:

from django.shortcuts import render
from .forms import UploadFileForm

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return render(request, 'uploads/success.html')
    else:
        form = UploadFileForm()
    return render(request, 'uploads/upload.html', {'form': form})

def handle_uploaded_file(file):
    with open(f'media/{file.name}', 'wb+') as destination:
        for chunk in file.chunks():
            destination.write(chunk)
                

Creating Templates

Let's create templates for the file upload form and success page. First, create the upload.html template:

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

Next, create the success.html template:

<!DOCTYPE html>
<html>
<head>
    <title>Success</title>
</head>
<body>
    <h2>File uploaded successfully!</h2>
</body>
</html>
                

Configuring URLs

Finally, let's configure the URLs to point to our view. Update uploads/urls.py:

from django.urls import path
from . import views

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

Include the uploads app URLs in the main 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')),
]
                

Testing the File Upload

Run the development server:

python manage.py runserver

Navigate to http://127.0.0.1:8000/uploads/upload/ to see the upload form. Try uploading files to see the validation in action.

Conclusion

In this tutorial, we learned how to set up file upload validation in a Django application. We covered how to check file size and type to ensure only valid files are uploaded. Proper file validation is essential for maintaining the security and integrity of your application.