В данном документе собрана краткая выжимка из документации.
Виды формсетов
BaseFormSet
Определён в django.forms.formsets.
Конструктор:
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList)
Полезные функции из модуля:
- formset_factory(form, formset=BaseFormSet, extra=1, can_order=False, can_delete=False, max_num=None)
- all_valid(formsets)
BaseModelFormSet
Определён в django.forms.models.
Конструктор:
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
queryset=None, **kwargs):
Полезные функции из модуля:
- modelformset_factory(model, form=ModelForm, formfield_callback=None, formset=BaseModelFormSet, extra=1, can_delete=False, can_order=False, max_num=None, fields=None, exclude=None)
BaseInlineFormSet
Определён в django.forms.models.
Конструктор:
def __init__(self, data=None, files=None, instance=None,
save_as_new=False, prefix=None, queryset=None)
Полезные функции из модуля:
- inlineformset_factory(parent_model, model, form=ModelForm, formset=BaseInlineFormSet, fk_name=None, fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None)
Работа с формсетами
>>> from django import forms
>>> class TestForm(forms.Form):
... pole = forms.CharField(max_length=10)
...
>>> from django.forms.formsets import formset_factory
>>> fs = formset_factory(TestForm)
>>> z = fs(None, prefix='voucher')
>>> print z
<input type="hidden" name="voucher-TOTAL_FORMS" value="1" id="id_voucher-TOTAL_FORMS" />
<input type="hidden" name="voucher-INITIAL_FORMS" value="0" id="id_voucher-INITIAL_FORMS" />
<input type="hidden" name="voucher-MAX_NUM_FORMS" id="id_voucher-MAX_NUM_FORMS" />
<tr>
<th><label for="id_voucher-0-pole">Pole:</label></th>
<td><input id="id_voucher-0-pole" type="text" name="voucher-0-pole" maxlength="10" /></td>
</tr>