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