Django File Upload Examples | Simple Guide

Explore three practical examples of Django file upload to enhance your web applications with file handling capabilities.
By Taylor

Introduction to Django File Upload

File uploads are a common requirement in web applications. Django, a high-level Python web framework, provides robust tools to handle file uploads seamlessly. In this guide, we will explore three practical examples of Django file upload, each demonstrating different scenarios where file handling can be beneficial. Whether you’re building a profile picture upload feature or a document management system, these examples will help you understand how to implement file uploads effectively.

Example 1: User Profile Picture Upload

Use Case

In many web applications, users may want to upload a profile picture. This example will demonstrate how to create a simple form for users to upload their profile images.

## models.py
from django.db import models

class UserProfile(models.Model):
    username = models.CharField(max_length=100)
    profile_picture = models.ImageField(upload_to='profile_pics/')

## forms.py
from django import forms
from .models import UserProfile

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['username', 'profile_picture']

## views.py
from django.shortcuts import render, redirect
from .forms import UserProfileForm

def upload_profile_picture(request):
    if request.method == 'POST':
        form = UserProfileForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('success_page')
    else:
        form = UserProfileForm()
    return render(request, 'upload_profile.html', {'form': form})

Notes

  • Ensure that you have the Pillow library installed to handle image uploads: pip install Pillow.
  • Remember to add the media settings in your Django settings file to serve uploaded files during development.

Example 2: Document Upload System

Use Case

Creating a document upload system for an online application can streamline file sharing. This example will show how users can upload various document files, such as PDFs or DOCs.

## models.py
from django.db import models

class Document(models.Model):
    title = models.CharField(max_length=200)
    file = models.FileField(upload_to='documents/')

## forms.py
from django import forms
from .models import Document

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ['title', 'file']

## views.py
from django.shortcuts import render, redirect
from .forms import DocumentForm

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

Notes

  • You can customize the allowed file types by setting the upload_to parameter and performing additional validation in your form.
  • Make sure to handle file size limits by configuring the FILE_UPLOAD_MAX_MEMORY_SIZE in your settings.

Example 3: Multiple File Upload

Use Case

Sometimes, users may need to upload multiple files at once, such as images for a gallery. This example will illustrate how to allow users to upload multiple files using Django.

## models.py
from django.db import models

class Gallery(models.Model):
    title = models.CharField(max_length=200)
    images = models.FileField(upload_to='gallery_images/')

## forms.py
from django import forms
from .models import Gallery

class GalleryForm(forms.ModelForm):
    class Meta:
        model = Gallery
        fields = ['title', 'images']
    images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

## views.py
from django.shortcuts import render, redirect
from .forms import GalleryForm

def upload_gallery(request):
    if request.method == 'POST':
        form = GalleryForm(request.POST, request.FILES)
        if form.is_valid():
            for file in request.FILES.getlist('images'):
                Gallery.objects.create(title=form.cleaned_data['title'], images=file)
            return redirect('success_page')
    else:
        form = GalleryForm()
    return render(request, 'upload_gallery.html', {'form': form})

Notes

  • This example uses request.FILES.getlist() to handle multiple file uploads.
  • Ensure your front-end supports multiple file selection, typically through an <input type='file' multiple> element.

By implementing these examples of Django file upload, you can enhance your web applications with the ability to handle user-generated content efficiently. Happy coding!