mirror of
https://github.com/django/django.git
synced 2025-08-03 10:34:04 +00:00
Fixed #18166 -- Added form_kwargs support to formsets.
By specifying form_kwargs when instantiating the formset, or overriding the `get_form_kwargs` method on a formset class, you can pass extra keyword arguments to the underlying `Form` instances. Includes tests and documentation update.
This commit is contained in:
parent
57dbc87ade
commit
238e2ac369
3 changed files with 87 additions and 2 deletions
|
@ -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
|
||||
--------------------------------------
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue