About Extra Parameters of Formset Forms

Pass extra parameters to formset forms using the form_kwargs argument. For example, pass the request parameter to a comment formset like so:

comments/views.py

# in some view for batch comment moderation:
CommentFormSet = modelformset_factory(
    Comment, form=CommentForm, extra=1, can_delete=1
)
comment_formset = CommentFormSet(
    queryset=Comment.objects.none(),
    form_kwargs={"request": request},
)

comments/forms.py

from django import forms
from .models import Comment

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = "__all__"
    def __init__(request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        ...

Tips and Tricks Programming Django 5.x Django 4.2 Django 3.2 Python 3