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

1
2
3
4
5
6
7
8
# 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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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 4.x Django 3.2 Django 2.2 Python 3