File Uploads (Django)

File uploads in Django use FileField or ImageField on a model to store user-submitted files. The file is saved under MEDIA_ROOT, and the field stores its path; forms must use enctype multipart and pass request.FILES.

Django

To accept uploads you add a FileField(upload_to='docs/') or ImageField to a model. The actual file is written to disk under MEDIA_ROOT (in the upload_to subfolder), and the database column stores just the relative path, which you access as instance.file.url for linking.

The HTML form needs enctype='multipart/form-data', and in the view you must pass both POST data and files to the form: Form(request.POST, request.FILES). A ModelForm with the FileField then handles saving the upload when you call form.save().

Validate uploads for safety: restrict size, check the content type/extension, and never trust the original filename. ImageField additionally requires Pillow and validates that the upload is a real image. For scale, store files in cloud object storage via a custom storage backend rather than local disk.

Syntax

doc = models.FileField(upload_to="docs/")

Examples

Python

class Document(models.Model):
    file = models.FileField(upload_to="docs/%Y/%m/")

def upload(request):
    form = DocumentForm(request.POST, request.FILES)
    if form.is_valid():
        form.save()
    return render(request, "upload.html", {"form": form})

Learn it in a lesson

See also

Back to the Dictionary