About Django Formsets and File Uploads

If you have a form and formsets where the formsets have file uploads, you must set enctype="multipart/form-data" to the main form for the uploads to work. Here's how to set it with django-crispy-forms:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from django import forms
from crispy_forms.helper import FormHelper

class MainForm(forms.Form):
    # ...
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.form_method = "POST"
        self.helper.attrs = {
            "enctype": "multipart/form-data",
        }
        # ...

If the main form has file upload fields, django-crispy-forms is smart enough to add that attribute for you.

Tips and Tricks Programming Development Django 5.x Django 4.2 Django 3.2 HTML5 django-crispy-forms