Fixed #8234: Corrected typo in docs/cache.txt
[django.git] / docs / modelforms.txt
blob1be7c3a88221fa71f14efb6eaf6fc12127d8741e
1 =======================
2 Using forms with models
3 =======================
5 ``ModelForm``
6 =============
8 If you're building a database-driven app, chances are you'll have forms that
9 map closely to Django models. For instance, you might have a ``BlogComment``
10 model, and you want to create a form that lets people submit comments. In this
11 case, it would be redundant to define the field types in your form, because
12 you've already defined the fields in your model.
14 For this reason, Django provides a helper class that let you create a ``Form``
15 class from a Django model.
17 For example::
19     >>> from django.forms import ModelForm
21     # Create the form class.
22     >>> class ArticleForm(ModelForm):
23     ...     class Meta:
24     ...         model = Article
26     # Creating a form to add an article.
27     >>> form = ArticleForm()
29     # Creating a form to change an existing article.
30     >>> article = Article.objects.get(pk=1)
31     >>> form = ArticleForm(instance=article)
33 Field types
34 -----------
36 The generated ``Form`` class will have a form field for every model field. Each
37 model field has a corresponding default form field. For example, a
38 ``CharField`` on a model is represented as a ``CharField`` on a form. A
39 model ``ManyToManyField`` is represented as a ``MultipleChoiceField``. Here is
40 the full list of conversions:
42     ===============================  ========================================
43     Model field                      Form field
44     ===============================  ========================================
45     ``AutoField``                    Not represented in the form
46     ``BooleanField``                 ``BooleanField``
47     ``CharField``                    ``CharField`` with ``max_length`` set to
48                                      the model field's ``max_length``
49     ``CommaSeparatedIntegerField``   ``CharField``
50     ``DateField``                    ``DateField``
51     ``DateTimeField``                ``DateTimeField``
52     ``DecimalField``                 ``DecimalField``
53     ``EmailField``                   ``EmailField``
54     ``FileField``                    ``FileField``
55     ``FilePathField``                ``CharField``
56     ``FloatField``                   ``FloatField``
57     ``ForeignKey``                   ``ModelChoiceField`` (see below)
58     ``ImageField``                   ``ImageField``
59     ``IntegerField``                 ``IntegerField``
60     ``IPAddressField``               ``IPAddressField``
61     ``ManyToManyField``              ``ModelMultipleChoiceField`` (see
62                                      below)
63     ``NullBooleanField``             ``CharField``
64     ``PhoneNumberField``             ``USPhoneNumberField``
65                                      (from ``django.contrib.localflavor.us``)
66     ``PositiveIntegerField``         ``IntegerField``
67     ``PositiveSmallIntegerField``    ``IntegerField``
68     ``SlugField``                    ``CharField``
69     ``SmallIntegerField``            ``IntegerField``
70     ``TextField``                    ``CharField`` with ``widget=Textarea``
71     ``TimeField``                    ``TimeField``
72     ``URLField``                     ``URLField`` with ``verify_exists`` set
73                                      to the model field's ``verify_exists``
74     ``USStateField``                 ``CharField`` with
75                                      ``widget=USStateSelect``
76                                      (``USStateSelect`` is from
77                                      ``django.contrib.localflavor.us``)
78     ``XMLField``                     ``CharField`` with ``widget=Textarea``
79     ===============================  ========================================
82 .. note::
83     The ``FloatField`` form field and ``DecimalField`` model and form fields
84     are new in the development version.
86 As you might expect, the ``ForeignKey`` and ``ManyToManyField`` model field
87 types are special cases:
89     * ``ForeignKey`` is represented by ``django.forms.ModelChoiceField``,
90       which is a ``ChoiceField`` whose choices are a model ``QuerySet``.
92     * ``ManyToManyField`` is represented by
93       ``django.forms.ModelMultipleChoiceField``, which is a
94       ``MultipleChoiceField`` whose choices are a model ``QuerySet``.
96 In addition, each generated form field has attributes set as follows:
98     * If the model field has ``blank=True``, then ``required`` is set to
99       ``False`` on the form field. Otherwise, ``required=True``.
101     * The form field's ``label`` is set to the ``verbose_name`` of the model
102       field, with the first character capitalized.
104     * The form field's ``help_text`` is set to the ``help_text`` of the model
105       field.
107     * If the model field has ``choices`` set, then the form field's ``widget``
108       will be set to ``Select``, with choices coming from the model field's
109       ``choices``. The choices will normally include the blank choice which is
110       selected by default. If the field is required, this forces the user to
111       make a selection. The blank choice will not be included if the model
112       field has ``blank=False`` and an explicit ``default`` value (the
113       ``default`` value will be initially selected instead).
115 Finally, note that you can override the form field used for a given model
116 field. See `Overriding the default field types`_ below.
118 A full example
119 --------------
121 Consider this set of models::
123     from django.db import models
124     from django.forms import ModelForm
126     TITLE_CHOICES = (
127         ('MR', 'Mr.'),
128         ('MRS', 'Mrs.'),
129         ('MS', 'Ms.'),
130     )
132     class Author(models.Model):
133         name = models.CharField(max_length=100)
134         title = models.CharField(max_length=3, choices=TITLE_CHOICES)
135         birth_date = models.DateField(blank=True, null=True)
137         def __unicode__(self):
138             return self.name
140     class Book(models.Model):
141         name = models.CharField(max_length=100)
142         authors = models.ManyToManyField(Author)
144     class AuthorForm(ModelForm):
145         class Meta:
146             model = Author
148     class BookForm(ModelForm):
149         class Meta:
150             model = Book
152 With these models, the ``ModelForm`` subclasses above would be roughly
153 equivalent to this (the only difference being the ``save()`` method, which
154 we'll discuss in a moment.)::
156     class AuthorForm(forms.Form):
157         name = forms.CharField(max_length=100)
158         title = forms.CharField(max_length=3,
159                     widget=forms.Select(choices=TITLE_CHOICES))
160         birth_date = forms.DateField(required=False)
162     class BookForm(forms.Form):
163         name = forms.CharField(max_length=100)
164         authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all())
166 The ``save()`` method
167 ---------------------
169 Every form produced by ``ModelForm`` also has a ``save()``
170 method. This method creates and saves a database object from the data
171 bound to the form. A subclass of ``ModelForm`` can accept an existing
172 model instance as the keyword argument ``instance``; if this is
173 supplied, ``save()`` will update that instance. If it's not supplied,
174 ``save()`` will create a new instance of the specified model::
176     # Create a form instance from POST data.
177     >>> f = ArticleForm(request.POST)
179     # Save a new Article object from the form's data.
180     >>> new_article = f.save()
182     # Create a form to edit an existing Article.
183     >>> a = Article.objects.get(pk=1)
184     >>> f = ArticleForm(instance=a)
185     >>> f.save()
187     # Create a form to edit an existing Article, but use
188     # POST data to populate the form.
189     >>> a = Article.objects.get(pk=1)
190     >>> f = ArticleForm(request.POST, instance=a)
191     >>> f.save()
193 Note that ``save()`` will raise a ``ValueError`` if the data in the form
194 doesn't validate -- i.e., ``if form.errors``.
196 This ``save()`` method accepts an optional ``commit`` keyword argument, which
197 accepts either ``True`` or ``False``. If you call ``save()`` with
198 ``commit=False``, then it will return an object that hasn't yet been saved to
199 the database. In this case, it's up to you to call ``save()`` on the resulting
200 model instance. This is useful if you want to do custom processing on the
201 object before saving it. ``commit`` is ``True`` by default.
203 Another side effect of using ``commit=False`` is seen when your model has
204 a many-to-many relation with another model. If your model has a many-to-many
205 relation and you specify ``commit=False`` when you save a form, Django cannot
206 immediately save the form data for the many-to-many relation. This is because
207 it isn't possible to save many-to-many data for an instance until the instance
208 exists in the database.
210 To work around this problem, every time you save a form using ``commit=False``,
211 Django adds a ``save_m2m()`` method to your ``ModelForm`` subclass. After
212 you've manually saved the instance produced by the form, you can invoke
213 ``save_m2m()`` to save the many-to-many form data. For example::
215     # Create a form instance with POST data.
216     >>> f = AuthorForm(request.POST)
218     # Create, but don't save the new author instance.
219     >>> new_author = f.save(commit=False)
221     # Modify the author in some way.
222     >>> new_author.some_field = 'some_value'
224     # Save the new instance.
225     >>> new_author.save()
227     # Now, save the many-to-many data for the form.
228     >>> f.save_m2m()
230 Calling ``save_m2m()`` is only required if you use ``save(commit=False)``.
231 When you use a simple ``save()`` on a form, all data -- including
232 many-to-many data -- is saved without the need for any additional method calls.
233 For example::
235     # Create a form instance with POST data.
236     >>> a = Author()
237     >>> f = AuthorForm(request.POST, instance=a)
239     # Create and save the new author instance. There's no need to do anything else.
240     >>> new_author = f.save()
242 Other than the ``save()`` and ``save_m2m()`` methods, a ``ModelForm``
243 works exactly the same way as any other ``forms`` form. For
244 example, the ``is_valid()`` method is used to check for validity, the
245 ``is_multipart()`` method is used to determine whether a form requires
246 multipart file upload (and hence whether ``request.FILES`` must be
247 passed to the form), etc. See `the standard forms documentation`_
248 for more information.
250 .. _the standard forms documentation: ../forms/
252 Using a subset of fields on the form
253 ------------------------------------
255 In some cases, you may not want all the model fields to appear on the generated
256 form. There are three ways of telling ``ModelForm`` to use only a subset of the
257 model fields:
259 1. Set ``editable=False`` on the model field. As a result, *any* form
260    created from the model via ``ModelForm`` will not include that
261    field.
263 2. Use the ``fields`` attribute of the ``ModelForm``'s inner ``Meta``
264    class.  This attribute, if given, should be a list of field names
265    to include in the form.
267 3. Use the ``exclude`` attribute of the ``ModelForm``'s inner ``Meta``
268    class.  This attribute, if given, should be a list of field names
269    to exclude from the form.
271 For example, if you want a form for the ``Author`` model (defined
272 above) that includes only the ``name`` and ``title`` fields, you would
273 specify ``fields`` or ``exclude`` like this::
275     class PartialAuthorForm(ModelForm):
276         class Meta:
277             model = Author
278             fields = ('name', 'title')
279     
280     class PartialAuthorForm(ModelForm):
281         class Meta:
282             model = Author
283             exclude = ('birth_date',)
285 Since the Author model has only 3 fields, 'name', 'title', and
286 'birth_date', the forms above will contain exactly the same fields.
288 .. note::
290     If you specify ``fields`` or ``exclude`` when creating a form with
291     ``ModelForm``, then the fields that are not in the resulting form will not
292     be set by the form's ``save()`` method. Django will prevent any attempt to
293     save an incomplete model, so if the model does not allow the missing fields
294     to be empty, and does not provide a default value for the missing fields,
295     any attempt to ``save()`` a ``ModelForm`` with missing fields will fail.
296     To avoid this failure, you must instantiate your model with initial values
297     for the missing, but required fields, or use ``save(commit=False)`` and
298     manually set any extra required fields::
300         instance = Instance(required_field='value')
301         form = InstanceForm(request.POST, instance=instance)
302         new_instance = form.save()
304         instance = form.save(commit=False)
305         instance.required_field = 'new value'
306         new_instance = instance.save()
308     See the `section on saving forms`_ for more details on using
309     ``save(commit=False)``.
311 .. _section on saving forms: `The save() method`_
313 Overriding the default field types
314 ----------------------------------
316 The default field types, as described in the `Field types`_ table above, are
317 sensible defaults. If you have a ``DateField`` in your model, chances are you'd
318 want that to be represented as a ``DateField`` in your form. But
319 ``ModelForm`` gives you the flexibility of changing the form field type
320 for a given model field. You do this by declaratively specifying fields like
321 you would in a regular ``Form``. Declared fields will override the default
322 ones generated by using the ``model`` attribute.
324 For example, if you wanted to use ``MyDateFormField`` for the ``pub_date``
325 field, you could do the following::
327     >>> class ArticleForm(ModelForm):
328     ...     pub_date = MyDateFormField()
329     ...
330     ...     class Meta:
331     ...         model = Article
333 If you want to override a field's default widget, then specify the ``widget``
334 parameter when declaring the form field::
336    >>> class ArticleForm(ModelForm):
337    ...     pub_date = DateField(widget=MyDateWidget())
338    ...
339    ...     class Meta:
340    ...         model = Article
342 Form inheritance
343 ----------------
345 As with basic forms, you can extend and reuse ``ModelForms`` by inheriting
346 them. This is useful if you need to declare extra fields or extra methods on a
347 parent class for use in a number of forms derived from models. For example,
348 using the previous ``ArticleForm`` class::
350     >>> class EnhancedArticleForm(ArticleForm):
351     ...     def clean_pub_date(self):
352     ...         ...
354 This creates a form that behaves identically to ``ArticleForm``, except there's
355 some extra validation and cleaning for the ``pub_date`` field.
357 You can also subclass the parent's ``Meta`` inner class if you want to change
358 the ``Meta.fields`` or ``Meta.excludes`` lists::
360     >>> class RestrictedArticleForm(EnhancedArticleForm):
361     ...     class Meta(ArticleForm.Meta):
362     ...         exclude = ['body']
364 This adds the extra method from the ``EnhancedArticleForm`` and modifies
365 the original ``ArticleForm.Meta`` to remove one field.
367 There are a couple of things to note, however.
369  * Normal Python name resolution rules apply. If you have multiple base
370    classes that declare a ``Meta`` inner class, only the first one will be
371    used. This means the child's ``Meta``, if it exists, otherwise the
372    ``Meta`` of the first parent, etc.
374  * For technical reasons, a subclass cannot inherit from both a ``ModelForm``
375    and a ``Form`` simultaneously.
377 Chances are these notes won't affect you unless you're trying to do something
378 tricky with subclassing.
380 Model Formsets
381 ==============
383 Similar to regular formsets there are a couple enhanced formset classes that
384 provide all the right things to work with your models. Lets reuse the
385 ``Author`` model from above::
387     >>> from django.forms.models import modelformset_factory
388     >>> AuthorFormSet = modelformset_factory(Author)
390 This will create a formset that is capable of working with the data associated
391 to the ``Author`` model. It works just like a regular formset::
393     >>> formset = AuthorFormSet()
394     >>> print formset
395     <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" />
396     <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>
397     <tr><th><label for="id_form-0-title">Title:</label></th><td><select name="form-0-title" id="id_form-0-title">
398     <option value="" selected="selected">---------</option>
399     <option value="MR">Mr.</option>
400     <option value="MRS">Mrs.</option>
401     <option value="MS">Ms.</option>
402     </select></td></tr>
403     <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>
405 .. note::
406     One thing to note is that ``modelformset_factory`` uses ``formset_factory``
407     and by default uses ``can_delete=True``.
409 Changing the queryset
410 ---------------------
412 By default when you create a formset from a model the queryset will be all
413 objects in the model. This is best shown as ``Author.objects.all()``. This is
414 configurable::
416     >>> formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O'))
418 Alternatively, you can use a subclassing based approach::
420     from django.forms.models import BaseModelFormSet
421     
422     class BaseAuthorFormSet(BaseModelFormSet):
423         def get_queryset(self):
424             return super(BaseAuthorFormSet, self).get_queryset().filter(name__startswith='O')
426 Then your ``BaseAuthorFormSet`` would be passed into the factory function to
427 be used as a base::
429     >>> AuthorFormSet = modelformset_factory(Author, formset=BaseAuthorFormSet)
431 Saving objects in the formset
432 -----------------------------
434 Similar to a ``ModelForm`` you can save the data into the model. This is done
435 with the ``save()`` method on the formset::
437     # create a formset instance with POST data.
438     >>> formset = AuthorFormSet(request.POST)
439     
440     # assuming all is valid, save the data
441     >>> instances = formset.save()
443 The ``save()`` method will return the instances that have been saved to the
444 database. If an instance did not change in the bound data it will not be
445 saved to the database and not found in ``instances`` in the above example.
447 You can optionally pass in ``commit=False`` to ``save()`` to only return the
448 model instances without any database interaction::
450     # don't save to the database
451     >>> instances = formset.save(commit=False)
452     >>> for instance in instances:
453     ...     # do something with instance
454     ...     instance.save()
456 This gives you the ability to attach data to the instances before saving them
457 to the database. If your formset contains a ``ManyToManyField`` you will also
458 need to make a call to ``formset.save_m2m()`` to ensure the many-to-many
459 relationships are saved properly.
461 Limiting the number of objects editable
462 ---------------------------------------
464 Similar to regular formsets you can use the ``max_num`` parameter to
465 ``modelformset_factory`` to limit the number of forms displayed. With
466 model formsets this will properly limit the query to only select the maximum
467 number of objects needed::
469     >>> Author.objects.order_by('name')
470     [<Author: Charles Baudelaire>, <Author: Paul Verlaine>, <Author: Walt Whitman>]
471     
472     >>> AuthorFormSet = modelformset_factory(Author, max_num=2, extra=1)
473     >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
474     >>> formset.initial
475     [{'id': 1, 'name': u'Charles Baudelaire'}, {'id': 3, 'name': u'Paul Verlaine'}]
477 If the value of ``max_num`` is less than the total objects returned it will
478 fill the rest with extra forms::
480     >>> AuthorFormSet = modelformset_factory(Author, max_num=4, extra=1)
481     >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
482     >>> for form in formset.forms:
483     ...     print form.as_table()
484     <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>
485     <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>
486     <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>
487     <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>
489 Using ``inlineformset_factory``
490 -------------------------------
492 The ``inlineformset_factory`` is a helper to a common usage pattern of working
493 with related objects through a foreign key. Suppose you have two models
494 ``Author`` and ``Book``. You want to create a formset that works with the
495 books of a specific author. Here is how you could accomplish this::
497     >>> from django.forms.models import inlineformset_factory
498     >>> BookFormSet = inlineformset_factory(Author, Book)
499     >>> author = Author.objects.get(name=u'Orson Scott Card')
500     >>> formset = BookFormSet(instance=author)