Merge pull request #4757 from sergei-maertens/ticket_18166

Fixed #18166 -- Added ability to pass kwargs to the form constructor in a formset.
This commit is contained in:
Russell Keith-Magee 2015-06-05 11:10:28 +01:00
commit fe21fb810a
3 changed files with 87 additions and 2 deletions

View file

@ -238,6 +238,8 @@ pre-filled, and is also used to determine how many forms are required. You
will probably never need to override either of these methods, so please be
sure you understand what they do before doing so.
.. _empty_form:
``empty_form``
~~~~~~~~~~~~~~
@ -533,6 +535,43 @@ default fields/attributes of the order and deletion fields::
<tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" id="id_form-0-pub_date" /></td></tr>
<tr><th><label for="id_form-0-my_field">My field:</label></th><td><input type="text" name="form-0-my_field" id="id_form-0-my_field" /></td></tr>
Passing custom parameters to formset forms
------------------------------------------
Sometimes your form class takes custom parameters, like ``MyArticleForm``.
You can pass this parameter when instantiating the formset::
>>> from django.forms.formsets import BaseFormSet
>>> from django.forms.formsets import formset_factory
>>> from myapp.forms import ArticleForm
>>> class MyArticleForm(ArticleForm):
... def __init__(self, *args, **kwargs):
... self.user = kwargs.pop('user')
... super(MyArticleForm, self).__init__(*args, **kwargs)
>>> ArticleFormSet = formset_factory(MyArticleForm)
>>> formset = ArticleFormSet(form_kwargs={'user': request.user})
The ``form_kwargs`` may also depend on the specific form instance. The formset
base class provides a ``get_form_kwargs`` method. The method takes a single
argument - the index of the form in the formset. The index is ``None`` for the
:ref:`empty_form`::
>>> from django.forms.formsets import BaseFormSet
>>> from django.forms.formsets import formset_factory
>>> class BaseArticleFormSet(BaseFormSet):
... def get_form_kwargs(self, index):
... kwargs = super(BaseArticleFormSet, self).get_form_kwargs(index)
... kwargs['custom_kwarg'] = index
... return kwargs
.. versionadded:: 1.9
The ``form_kwargs`` argument was added.
Using a formset in views and templates
--------------------------------------