PageRenderTime 47ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/docs/topics/forms/modelforms.txt

https://code.google.com/p/mango-py/
Plain Text | 873 lines | 641 code | 232 blank | 0 comment | 0 complexity | 85304aa3da09c4b813260ab73c64f6e4 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. ==========================
  2. Creating forms from models
  3. ==========================
  4. .. module:: django.forms.models
  5. :synopsis: ModelForm and ModelFormset.
  6. .. currentmodule:: django.forms
  7. ``ModelForm``
  8. =============
  9. .. class:: ModelForm
  10. If you're building a database-driven app, chances are you'll have forms that
  11. map closely to Django models. For instance, you might have a ``BlogComment``
  12. model, and you want to create a form that lets people submit comments. In this
  13. case, it would be redundant to define the field types in your form, because
  14. you've already defined the fields in your model.
  15. For this reason, Django provides a helper class that let you create a ``Form``
  16. class from a Django model.
  17. For example::
  18. >>> from django.forms import ModelForm
  19. # Create the form class.
  20. >>> class ArticleForm(ModelForm):
  21. ... class Meta:
  22. ... model = Article
  23. # Creating a form to add an article.
  24. >>> form = ArticleForm()
  25. # Creating a form to change an existing article.
  26. >>> article = Article.objects.get(pk=1)
  27. >>> form = ArticleForm(instance=article)
  28. Field types
  29. -----------
  30. The generated ``Form`` class will have a form field for every model field. Each
  31. model field has a corresponding default form field. For example, a
  32. ``CharField`` on a model is represented as a ``CharField`` on a form. A
  33. model ``ManyToManyField`` is represented as a ``MultipleChoiceField``. Here is
  34. the full list of conversions:
  35. =============================== ========================================
  36. Model field Form field
  37. =============================== ========================================
  38. ``AutoField`` Not represented in the form
  39. ``BigIntegerField`` ``IntegerField`` with ``min_value`` set
  40. to -9223372036854775808 and ``max_value``
  41. set to 9223372036854775807.
  42. ``BooleanField`` ``BooleanField``
  43. ``CharField`` ``CharField`` with ``max_length`` set to
  44. the model field's ``max_length``
  45. ``CommaSeparatedIntegerField`` ``CharField``
  46. ``DateField`` ``DateField``
  47. ``DateTimeField`` ``DateTimeField``
  48. ``DecimalField`` ``DecimalField``
  49. ``EmailField`` ``EmailField``
  50. ``FileField`` ``FileField``
  51. ``FilePathField`` ``CharField``
  52. ``FloatField`` ``FloatField``
  53. ``ForeignKey`` ``ModelChoiceField`` (see below)
  54. ``ImageField`` ``ImageField``
  55. ``IntegerField`` ``IntegerField``
  56. ``IPAddressField`` ``IPAddressField``
  57. ``ManyToManyField`` ``ModelMultipleChoiceField`` (see
  58. below)
  59. ``NullBooleanField`` ``CharField``
  60. ``PhoneNumberField`` ``USPhoneNumberField``
  61. (from ``django.contrib.localflavor.us``)
  62. ``PositiveIntegerField`` ``IntegerField``
  63. ``PositiveSmallIntegerField`` ``IntegerField``
  64. ``SlugField`` ``SlugField``
  65. ``SmallIntegerField`` ``IntegerField``
  66. ``TextField`` ``CharField`` with
  67. ``widget=forms.Textarea``
  68. ``TimeField`` ``TimeField``
  69. ``URLField`` ``URLField`` with ``verify_exists`` set
  70. to the model field's ``verify_exists``
  71. =============================== ========================================
  72. .. versionadded:: 1.2
  73. The ``BigIntegerField`` is new in Django 1.2.
  74. As you might expect, the ``ForeignKey`` and ``ManyToManyField`` model field
  75. types are special cases:
  76. * ``ForeignKey`` is represented by ``django.forms.ModelChoiceField``,
  77. which is a ``ChoiceField`` whose choices are a model ``QuerySet``.
  78. * ``ManyToManyField`` is represented by
  79. ``django.forms.ModelMultipleChoiceField``, which is a
  80. ``MultipleChoiceField`` whose choices are a model ``QuerySet``.
  81. In addition, each generated form field has attributes set as follows:
  82. * If the model field has ``blank=True``, then ``required`` is set to
  83. ``False`` on the form field. Otherwise, ``required=True``.
  84. * The form field's ``label`` is set to the ``verbose_name`` of the model
  85. field, with the first character capitalized.
  86. * The form field's ``help_text`` is set to the ``help_text`` of the model
  87. field.
  88. * If the model field has ``choices`` set, then the form field's ``widget``
  89. will be set to ``Select``, with choices coming from the model field's
  90. ``choices``. The choices will normally include the blank choice which is
  91. selected by default. If the field is required, this forces the user to
  92. make a selection. The blank choice will not be included if the model
  93. field has ``blank=False`` and an explicit ``default`` value (the
  94. ``default`` value will be initially selected instead).
  95. Finally, note that you can override the form field used for a given model
  96. field. See `Overriding the default field types or widgets`_ below.
  97. A full example
  98. --------------
  99. Consider this set of models::
  100. from django.db import models
  101. from django.forms import ModelForm
  102. TITLE_CHOICES = (
  103. ('MR', 'Mr.'),
  104. ('MRS', 'Mrs.'),
  105. ('MS', 'Ms.'),
  106. )
  107. class Author(models.Model):
  108. name = models.CharField(max_length=100)
  109. title = models.CharField(max_length=3, choices=TITLE_CHOICES)
  110. birth_date = models.DateField(blank=True, null=True)
  111. def __unicode__(self):
  112. return self.name
  113. class Book(models.Model):
  114. name = models.CharField(max_length=100)
  115. authors = models.ManyToManyField(Author)
  116. class AuthorForm(ModelForm):
  117. class Meta:
  118. model = Author
  119. class BookForm(ModelForm):
  120. class Meta:
  121. model = Book
  122. With these models, the ``ModelForm`` subclasses above would be roughly
  123. equivalent to this (the only difference being the ``save()`` method, which
  124. we'll discuss in a moment.)::
  125. from django import forms
  126. class AuthorForm(forms.Form):
  127. name = forms.CharField(max_length=100)
  128. title = forms.CharField(max_length=3,
  129. widget=forms.Select(choices=TITLE_CHOICES))
  130. birth_date = forms.DateField(required=False)
  131. class BookForm(forms.Form):
  132. name = forms.CharField(max_length=100)
  133. authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all())
  134. The ``is_valid()`` method and ``errors``
  135. ----------------------------------------
  136. .. versionchanged:: 1.2
  137. The first time you call ``is_valid()`` or access the ``errors`` attribute of a
  138. ``ModelForm`` has always triggered form validation, but as of Django 1.2, it
  139. will also trigger :ref:`model validation <validating-objects>`. This has the
  140. side-effect of cleaning the model you pass to the ``ModelForm`` constructor.
  141. For instance, calling ``is_valid()`` on your form will convert any date fields
  142. on your model to actual date objects.
  143. The ``save()`` method
  144. ---------------------
  145. Every form produced by ``ModelForm`` also has a ``save()``
  146. method. This method creates and saves a database object from the data
  147. bound to the form. A subclass of ``ModelForm`` can accept an existing
  148. model instance as the keyword argument ``instance``; if this is
  149. supplied, ``save()`` will update that instance. If it's not supplied,
  150. ``save()`` will create a new instance of the specified model::
  151. # Create a form instance from POST data.
  152. >>> f = ArticleForm(request.POST)
  153. # Save a new Article object from the form's data.
  154. >>> new_article = f.save()
  155. # Create a form to edit an existing Article.
  156. >>> a = Article.objects.get(pk=1)
  157. >>> f = ArticleForm(instance=a)
  158. >>> f.save()
  159. # Create a form to edit an existing Article, but use
  160. # POST data to populate the form.
  161. >>> a = Article.objects.get(pk=1)
  162. >>> f = ArticleForm(request.POST, instance=a)
  163. >>> f.save()
  164. Note that ``save()`` will raise a ``ValueError`` if the data in the form
  165. doesn't validate -- i.e., if form.errors evaluates to True.
  166. This ``save()`` method accepts an optional ``commit`` keyword argument, which
  167. accepts either ``True`` or ``False``. If you call ``save()`` with
  168. ``commit=False``, then it will return an object that hasn't yet been saved to
  169. the database. In this case, it's up to you to call ``save()`` on the resulting
  170. model instance. This is useful if you want to do custom processing on the
  171. object before saving it, or if you want to use one of the specialized
  172. :ref:`model saving options <ref-models-force-insert>`. ``commit`` is ``True``
  173. by default.
  174. Another side effect of using ``commit=False`` is seen when your model has
  175. a many-to-many relation with another model. If your model has a many-to-many
  176. relation and you specify ``commit=False`` when you save a form, Django cannot
  177. immediately save the form data for the many-to-many relation. This is because
  178. it isn't possible to save many-to-many data for an instance until the instance
  179. exists in the database.
  180. To work around this problem, every time you save a form using ``commit=False``,
  181. Django adds a ``save_m2m()`` method to your ``ModelForm`` subclass. After
  182. you've manually saved the instance produced by the form, you can invoke
  183. ``save_m2m()`` to save the many-to-many form data. For example::
  184. # Create a form instance with POST data.
  185. >>> f = AuthorForm(request.POST)
  186. # Create, but don't save the new author instance.
  187. >>> new_author = f.save(commit=False)
  188. # Modify the author in some way.
  189. >>> new_author.some_field = 'some_value'
  190. # Save the new instance.
  191. >>> new_author.save()
  192. # Now, save the many-to-many data for the form.
  193. >>> f.save_m2m()
  194. Calling ``save_m2m()`` is only required if you use ``save(commit=False)``.
  195. When you use a simple ``save()`` on a form, all data -- including
  196. many-to-many data -- is saved without the need for any additional method calls.
  197. For example::
  198. # Create a form instance with POST data.
  199. >>> a = Author()
  200. >>> f = AuthorForm(request.POST, instance=a)
  201. # Create and save the new author instance. There's no need to do anything else.
  202. >>> new_author = f.save()
  203. Other than the ``save()`` and ``save_m2m()`` methods, a ``ModelForm`` works
  204. exactly the same way as any other ``forms`` form. For example, the
  205. ``is_valid()`` method is used to check for validity, the ``is_multipart()``
  206. method is used to determine whether a form requires multipart file upload (and
  207. hence whether ``request.FILES`` must be passed to the form), etc. See
  208. :ref:`binding-uploaded-files` for more information.
  209. Using a subset of fields on the form
  210. ------------------------------------
  211. In some cases, you may not want all the model fields to appear on the generated
  212. form. There are three ways of telling ``ModelForm`` to use only a subset of the
  213. model fields:
  214. 1. Set ``editable=False`` on the model field. As a result, *any* form
  215. created from the model via ``ModelForm`` will not include that
  216. field.
  217. 2. Use the ``fields`` attribute of the ``ModelForm``'s inner ``Meta``
  218. class. This attribute, if given, should be a list of field names
  219. to include in the form. The order in which the fields names are specified
  220. in that list is respected when the form renders them.
  221. 3. Use the ``exclude`` attribute of the ``ModelForm``'s inner ``Meta``
  222. class. This attribute, if given, should be a list of field names
  223. to exclude from the form.
  224. For example, if you want a form for the ``Author`` model (defined
  225. above) that includes only the ``name`` and ``title`` fields, you would
  226. specify ``fields`` or ``exclude`` like this::
  227. class PartialAuthorForm(ModelForm):
  228. class Meta:
  229. model = Author
  230. fields = ('name', 'title')
  231. class PartialAuthorForm(ModelForm):
  232. class Meta:
  233. model = Author
  234. exclude = ('birth_date',)
  235. Since the Author model has only 3 fields, 'name', 'title', and
  236. 'birth_date', the forms above will contain exactly the same fields.
  237. .. note::
  238. If you specify ``fields`` or ``exclude`` when creating a form with
  239. ``ModelForm``, then the fields that are not in the resulting form will not
  240. be set by the form's ``save()`` method. Django will prevent any attempt to
  241. save an incomplete model, so if the model does not allow the missing fields
  242. to be empty, and does not provide a default value for the missing fields,
  243. any attempt to ``save()`` a ``ModelForm`` with missing fields will fail.
  244. To avoid this failure, you must instantiate your model with initial values
  245. for the missing, but required fields::
  246. author = Author(title='Mr')
  247. form = PartialAuthorForm(request.POST, instance=author)
  248. form.save()
  249. Alternatively, you can use ``save(commit=False)`` and manually set
  250. any extra required fields::
  251. form = PartialAuthorForm(request.POST)
  252. author = form.save(commit=False)
  253. author.title = 'Mr'
  254. author.save()
  255. See the `section on saving forms`_ for more details on using
  256. ``save(commit=False)``.
  257. .. _section on saving forms: `The save() method`_
  258. Overriding the default field types or widgets
  259. ---------------------------------------------
  260. .. versionadded:: 1.2
  261. The ``widgets`` attribute is new in Django 1.2.
  262. The default field types, as described in the `Field types`_ table above, are
  263. sensible defaults. If you have a ``DateField`` in your model, chances are you'd
  264. want that to be represented as a ``DateField`` in your form. But
  265. ``ModelForm`` gives you the flexibility of changing the form field type and
  266. widget for a given model field.
  267. To specify a custom widget for a field, use the ``widgets`` attribute of the
  268. inner ``Meta`` class. This should be a dictionary mapping field names to widget
  269. classes or instances.
  270. For example, if you want the a ``CharField`` for the ``name``
  271. attribute of ``Author`` to be represented by a ``<textarea>`` instead
  272. of its default ``<input type="text">``, you can override the field's
  273. widget::
  274. from django.forms import ModelForm, Textarea
  275. class AuthorForm(ModelForm):
  276. class Meta:
  277. model = Author
  278. fields = ('name', 'title', 'birth_date')
  279. widgets = {
  280. 'name': Textarea(attrs={'cols': 80, 'rows': 20}),
  281. }
  282. The ``widgets`` dictionary accepts either widget instances (e.g.,
  283. ``Textarea(...)``) or classes (e.g., ``Textarea``).
  284. If you want to further customize a field -- including its type, label, etc. --
  285. you can do this by declaratively specifying fields like you would in a regular
  286. ``Form``. Declared fields will override the default ones generated by using the
  287. ``model`` attribute.
  288. For example, if you wanted to use ``MyDateFormField`` for the ``pub_date``
  289. field, you could do the following::
  290. class ArticleForm(ModelForm):
  291. pub_date = MyDateFormField()
  292. class Meta:
  293. model = Article
  294. If you want to override a field's default label, then specify the ``label``
  295. parameter when declaring the form field::
  296. >>> class ArticleForm(ModelForm):
  297. ... pub_date = DateField(label='Publication date')
  298. ...
  299. ... class Meta:
  300. ... model = Article
  301. .. note::
  302. If you explicitly instantiate a form field like this, Django assumes that you
  303. want to completely define its behavior; therefore, default attributes (such as
  304. ``max_length`` or ``required``) are not drawn from the corresponding model. If
  305. you want to maintain the behavior specified in the model, you must set the
  306. relevant arguments explicitly when declaring the form field.
  307. For example, if the ``Article`` model looks like this::
  308. class Article(models.Model):
  309. headline = models.CharField(max_length=200, null=True, blank=True,
  310. help_text="Use puns liberally")
  311. content = models.TextField()
  312. and you want to do some custom validation for ``headline``, while keeping
  313. the ``blank`` and ``help_text`` values as specified, you might define
  314. ``ArticleForm`` like this::
  315. class ArticleForm(ModelForm):
  316. headline = MyFormField(max_length=200, required=False,
  317. help_text="Use puns liberally")
  318. class Meta:
  319. model = Article
  320. See the :doc:`form field documentation </ref/forms/fields>` for more information
  321. on fields and their arguments.
  322. Changing the order of fields
  323. ----------------------------
  324. By default, a ``ModelForm`` will render fields in the same order that they are
  325. defined on the model, with ``ManyToManyField`` instances appearing last. If
  326. you want to change the order in which fields are rendered, you can use the
  327. ``fields`` attribute on the ``Meta`` class.
  328. The ``fields`` attribute defines the subset of model fields that will be
  329. rendered, and the order in which they will be rendered. For example given this
  330. model::
  331. class Book(models.Model):
  332. author = models.ForeignKey(Author)
  333. title = models.CharField(max_length=100)
  334. the ``author`` field would be rendered first. If we wanted the title field
  335. to be rendered first, we could specify the following ``ModelForm``::
  336. >>> class BookForm(ModelForm):
  337. ... class Meta:
  338. ... model = Book
  339. ... fields = ('title', 'author')
  340. .. _overriding-modelform-clean-method:
  341. Overriding the clean() method
  342. -----------------------------
  343. You can override the ``clean()`` method on a model form to provide additional
  344. validation in the same way you can on a normal form.
  345. In this regard, model forms have two specific characteristics when compared to
  346. forms:
  347. By default the ``clean()`` method validates the uniqueness of fields that are
  348. marked as ``unique``, ``unique_together`` or ``unique_for_date|month|year`` on
  349. the model. Therefore, if you would like to override the ``clean()`` method and
  350. maintain the default validation, you must call the parent class's ``clean()``
  351. method.
  352. Also, a model form instance bound to a model object will contain a
  353. ``self.instance`` attribute that gives model form methods access to that
  354. specific model instance.
  355. Form inheritance
  356. ----------------
  357. As with basic forms, you can extend and reuse ``ModelForms`` by inheriting
  358. them. This is useful if you need to declare extra fields or extra methods on a
  359. parent class for use in a number of forms derived from models. For example,
  360. using the previous ``ArticleForm`` class::
  361. >>> class EnhancedArticleForm(ArticleForm):
  362. ... def clean_pub_date(self):
  363. ... ...
  364. This creates a form that behaves identically to ``ArticleForm``, except there's
  365. some extra validation and cleaning for the ``pub_date`` field.
  366. You can also subclass the parent's ``Meta`` inner class if you want to change
  367. the ``Meta.fields`` or ``Meta.excludes`` lists::
  368. >>> class RestrictedArticleForm(EnhancedArticleForm):
  369. ... class Meta(ArticleForm.Meta):
  370. ... exclude = ('body',)
  371. This adds the extra method from the ``EnhancedArticleForm`` and modifies
  372. the original ``ArticleForm.Meta`` to remove one field.
  373. There are a couple of things to note, however.
  374. * Normal Python name resolution rules apply. If you have multiple base
  375. classes that declare a ``Meta`` inner class, only the first one will be
  376. used. This means the child's ``Meta``, if it exists, otherwise the
  377. ``Meta`` of the first parent, etc.
  378. * For technical reasons, a subclass cannot inherit from both a ``ModelForm``
  379. and a ``Form`` simultaneously.
  380. Chances are these notes won't affect you unless you're trying to do something
  381. tricky with subclassing.
  382. Interaction with model validation
  383. ---------------------------------
  384. As part of its validation process, ``ModelForm`` will call the ``clean()``
  385. method of each field on your model that has a corresponding field on your form.
  386. If you have excluded any model fields, validation will not be run on those
  387. fields. See the :doc:`form validation </ref/forms/validation>` documentation
  388. for more on how field cleaning and validation work. Also, your model's
  389. ``clean()`` method will be called before any uniqueness checks are made. See
  390. :ref:`Validating objects <validating-objects>` for more information on the
  391. model's ``clean()`` hook.
  392. .. _model-formsets:
  393. Model formsets
  394. ==============
  395. Like :doc:`regular formsets </topics/forms/formsets>`, Django provides a couple
  396. of enhanced formset classes that make it easy to work with Django models. Let's
  397. reuse the ``Author`` model from above::
  398. >>> from django.forms.models import modelformset_factory
  399. >>> AuthorFormSet = modelformset_factory(Author)
  400. This will create a formset that is capable of working with the data associated
  401. with the ``Author`` model. It works just like a regular formset::
  402. >>> formset = AuthorFormSet()
  403. >>> print formset
  404. <input type="hidden" name="form-TOTAL_FORMS" value="1" id="id_form-TOTAL_FORMS" /><input type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS" /><input type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS" />
  405. <tr><th><label for="id_form-0-name">Name:</label></th><td><input id="id_form-0-name" type="text" name="form-0-name" maxlength="100" /></td></tr>
  406. <tr><th><label for="id_form-0-title">Title:</label></th><td><select name="form-0-title" id="id_form-0-title">
  407. <option value="" selected="selected">---------</option>
  408. <option value="MR">Mr.</option>
  409. <option value="MRS">Mrs.</option>
  410. <option value="MS">Ms.</option>
  411. </select></td></tr>
  412. <tr><th><label for="id_form-0-birth_date">Birth date:</label></th><td><input type="text" name="form-0-birth_date" id="id_form-0-birth_date" /><input type="hidden" name="form-0-id" id="id_form-0-id" /></td></tr>
  413. .. note::
  414. ``modelformset_factory`` uses ``formset_factory`` to generate formsets.
  415. This means that a model formset is just an extension of a basic formset
  416. that knows how to interact with a particular model.
  417. Changing the queryset
  418. ---------------------
  419. By default, when you create a formset from a model, the formset will use a
  420. queryset that includes all objects in the model (e.g.,
  421. ``Author.objects.all()``). You can override this behavior by using the
  422. ``queryset`` argument::
  423. >>> formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O'))
  424. Alternatively, you can create a subclass that sets ``self.queryset`` in
  425. ``__init__``::
  426. from django.forms.models import BaseModelFormSet
  427. class BaseAuthorFormSet(BaseModelFormSet):
  428. def __init__(self, *args, **kwargs):
  429. super(BaseAuthorFormSet, self).__init__(*args, **kwargs)
  430. self.queryset = Author.objects.filter(name__startswith='O')
  431. Then, pass your ``BaseAuthorFormSet`` class to the factory function::
  432. >>> AuthorFormSet = modelformset_factory(Author, formset=BaseAuthorFormSet)
  433. If you want to return a formset that doesn't include *any* pre-existing
  434. instances of the model, you can specify an empty QuerySet::
  435. >>> AuthorFormSet(queryset=Author.objects.none())
  436. Controlling which fields are used with ``fields`` and ``exclude``
  437. -----------------------------------------------------------------
  438. By default, a model formset uses all fields in the model that are not marked
  439. with ``editable=False``. However, this can be overridden at the formset level::
  440. >>> AuthorFormSet = modelformset_factory(Author, fields=('name', 'title'))
  441. Using ``fields`` restricts the formset to use only the given fields.
  442. Alternatively, you can take an "opt-out" approach, specifying which fields to
  443. exclude::
  444. >>> AuthorFormSet = modelformset_factory(Author, exclude=('birth_date',))
  445. .. _saving-objects-in-the-formset:
  446. Saving objects in the formset
  447. -----------------------------
  448. As with a ``ModelForm``, you can save the data as a model object. This is done
  449. with the formset's ``save()`` method::
  450. # Create a formset instance with POST data.
  451. >>> formset = AuthorFormSet(request.POST)
  452. # Assuming all is valid, save the data.
  453. >>> instances = formset.save()
  454. The ``save()`` method returns the instances that have been saved to the
  455. database. If a given instance's data didn't change in the bound data, the
  456. instance won't be saved to the database and won't be included in the return
  457. value (``instances``, in the above example).
  458. Pass ``commit=False`` to return the unsaved model instances::
  459. # don't save to the database
  460. >>> instances = formset.save(commit=False)
  461. >>> for instance in instances:
  462. ... # do something with instance
  463. ... instance.save()
  464. This gives you the ability to attach data to the instances before saving them
  465. to the database. If your formset contains a ``ManyToManyField``, you'll also
  466. need to call ``formset.save_m2m()`` to ensure the many-to-many relationships
  467. are saved properly.
  468. .. _model-formsets-max-num:
  469. Limiting the number of editable objects
  470. ---------------------------------------
  471. .. versionchanged:: 1.2
  472. As with regular formsets, you can use the ``max_num`` and ``extra`` parameters
  473. to ``modelformset_factory`` to limit the number of extra forms displayed.
  474. ``max_num`` does not prevent existing objects from being displayed::
  475. >>> Author.objects.order_by('name')
  476. [<Author: Charles Baudelaire>, <Author: Paul Verlaine>, <Author: Walt Whitman>]
  477. >>> AuthorFormSet = modelformset_factory(Author, max_num=1)
  478. >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
  479. >>> [x.name for x in formset.get_queryset()]
  480. [u'Charles Baudelaire', u'Paul Verlaine', u'Walt Whitman']
  481. If the value of ``max_num`` is greater than the number of existing related
  482. objects, up to ``extra`` additional blank forms will be added to the formset,
  483. so long as the total number of forms does not exceed ``max_num``::
  484. >>> AuthorFormSet = modelformset_factory(Author, max_num=4, extra=2)
  485. >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
  486. >>> for form in formset:
  487. ... print form.as_table()
  488. <tr><th><label for="id_form-0-name">Name:</label></th><td><input id="id_form-0-name" type="text" name="form-0-name" value="Charles Baudelaire" maxlength="100" /><input type="hidden" name="form-0-id" value="1" id="id_form-0-id" /></td></tr>
  489. <tr><th><label for="id_form-1-name">Name:</label></th><td><input id="id_form-1-name" type="text" name="form-1-name" value="Paul Verlaine" maxlength="100" /><input type="hidden" name="form-1-id" value="3" id="id_form-1-id" /></td></tr>
  490. <tr><th><label for="id_form-2-name">Name:</label></th><td><input id="id_form-2-name" type="text" name="form-2-name" value="Walt Whitman" maxlength="100" /><input type="hidden" name="form-2-id" value="2" id="id_form-2-id" /></td></tr>
  491. <tr><th><label for="id_form-3-name">Name:</label></th><td><input id="id_form-3-name" type="text" name="form-3-name" maxlength="100" /><input type="hidden" name="form-3-id" id="id_form-3-id" /></td></tr>
  492. .. versionchanged:: 1.2
  493. A ``max_num`` value of ``None`` (the default) puts no limit on the number of
  494. forms displayed.
  495. Using a model formset in a view
  496. -------------------------------
  497. Model formsets are very similar to formsets. Let's say we want to present a
  498. formset to edit ``Author`` model instances::
  499. def manage_authors(request):
  500. AuthorFormSet = modelformset_factory(Author)
  501. if request.method == 'POST':
  502. formset = AuthorFormSet(request.POST, request.FILES)
  503. if formset.is_valid():
  504. formset.save()
  505. # do something.
  506. else:
  507. formset = AuthorFormSet()
  508. return render_to_response("manage_authors.html", {
  509. "formset": formset,
  510. })
  511. As you can see, the view logic of a model formset isn't drastically different
  512. than that of a "normal" formset. The only difference is that we call
  513. ``formset.save()`` to save the data into the database. (This was described
  514. above, in :ref:`saving-objects-in-the-formset`.)
  515. Overiding ``clean()`` on a ``model_formset``
  516. --------------------------------------------
  517. Just like with ``ModelForms``, by default the ``clean()`` method of a
  518. ``model_formset`` will validate that none of the items in the formset violate
  519. the unique constraints on your model (either ``unique``, ``unique_together`` or
  520. ``unique_for_date|month|year``). If you want to overide the ``clean()`` method
  521. on a ``model_formset`` and maintain this validation, you must call the parent
  522. class's ``clean`` method::
  523. class MyModelFormSet(BaseModelFormSet):
  524. def clean(self):
  525. super(MyModelFormSet, self).clean()
  526. # example custom validation across forms in the formset:
  527. for form in self.forms:
  528. # your custom formset validation
  529. Using a custom queryset
  530. -----------------------
  531. As stated earlier, you can override the default queryset used by the model
  532. formset::
  533. def manage_authors(request):
  534. AuthorFormSet = modelformset_factory(Author)
  535. if request.method == "POST":
  536. formset = AuthorFormSet(request.POST, request.FILES,
  537. queryset=Author.objects.filter(name__startswith='O'))
  538. if formset.is_valid():
  539. formset.save()
  540. # Do something.
  541. else:
  542. formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O'))
  543. return render_to_response("manage_authors.html", {
  544. "formset": formset,
  545. })
  546. Note that we pass the ``queryset`` argument in both the ``POST`` and ``GET``
  547. cases in this example.
  548. Using the formset in the template
  549. ---------------------------------
  550. .. highlight:: html+django
  551. There are three ways to render a formset in a Django template.
  552. First, you can let the formset do most of the work::
  553. <form method="post" action="">
  554. {{ formset }}
  555. </form>
  556. Second, you can manually render the formset, but let the form deal with
  557. itself::
  558. <form method="post" action="">
  559. {{ formset.management_form }}
  560. {% for form in formset %}
  561. {{ form }}
  562. {% endfor %}
  563. </form>
  564. When you manually render the forms yourself, be sure to render the management
  565. form as shown above. See the :ref:`management form documentation
  566. <understanding-the-managementform>`.
  567. Third, you can manually render each field::
  568. <form method="post" action="">
  569. {{ formset.management_form }}
  570. {% for form in formset %}
  571. {% for field in form %}
  572. {{ field.label_tag }}: {{ field }}
  573. {% endfor %}
  574. {% endfor %}
  575. </form>
  576. If you opt to use this third method and you don't iterate over the fields with
  577. a ``{% for %}`` loop, you'll need to render the primary key field. For example,
  578. if you were rendering the ``name`` and ``age`` fields of a model::
  579. <form method="post" action="">
  580. {{ formset.management_form }}
  581. {% for form in formset %}
  582. {{ form.id }}
  583. <ul>
  584. <li>{{ form.name }}</li>
  585. <li>{{ form.age }}</li>
  586. </ul>
  587. {% endfor %}
  588. </form>
  589. Notice how we need to explicitly render ``{{ form.id }}``. This ensures that
  590. the model formset, in the ``POST`` case, will work correctly. (This example
  591. assumes a primary key named ``id``. If you've explicitly defined your own
  592. primary key that isn't called ``id``, make sure it gets rendered.)
  593. .. highlight:: python
  594. Inline formsets
  595. ===============
  596. Inline formsets is a small abstraction layer on top of model formsets. These
  597. simplify the case of working with related objects via a foreign key. Suppose
  598. you have these two models::
  599. class Author(models.Model):
  600. name = models.CharField(max_length=100)
  601. class Book(models.Model):
  602. author = models.ForeignKey(Author)
  603. title = models.CharField(max_length=100)
  604. If you want to create a formset that allows you to edit books belonging to
  605. a particular author, you could do this::
  606. >>> from django.forms.models import inlineformset_factory
  607. >>> BookFormSet = inlineformset_factory(Author, Book)
  608. >>> author = Author.objects.get(name=u'Mike Royko')
  609. >>> formset = BookFormSet(instance=author)
  610. .. note::
  611. ``inlineformset_factory`` uses ``modelformset_factory`` and marks
  612. ``can_delete=True``.
  613. More than one foreign key to the same model
  614. -------------------------------------------
  615. If your model contains more than one foreign key to the same model, you'll
  616. need to resolve the ambiguity manually using ``fk_name``. For example, consider
  617. the following model::
  618. class Friendship(models.Model):
  619. from_friend = models.ForeignKey(Friend)
  620. to_friend = models.ForeignKey(Friend)
  621. length_in_months = models.IntegerField()
  622. To resolve this, you can use ``fk_name`` to ``inlineformset_factory``::
  623. >>> FriendshipFormSet = inlineformset_factory(Friend, Friendship, fk_name="from_friend")
  624. Using an inline formset in a view
  625. ---------------------------------
  626. You may want to provide a view that allows a user to edit the related objects
  627. of a model. Here's how you can do that::
  628. def manage_books(request, author_id):
  629. author = Author.objects.get(pk=author_id)
  630. BookInlineFormSet = inlineformset_factory(Author, Book)
  631. if request.method == "POST":
  632. formset = BookInlineFormSet(request.POST, request.FILES, instance=author)
  633. if formset.is_valid():
  634. formset.save()
  635. # Do something.
  636. else:
  637. formset = BookInlineFormSet(instance=author)
  638. return render_to_response("manage_books.html", {
  639. "formset": formset,
  640. })
  641. Notice how we pass ``instance`` in both the ``POST`` and ``GET`` cases.