Correct an example in docs/modelforms.txt, and fix some reST formatting
[django.git] / docs / modelforms.txt
bloba6babb1fe134bef426d5a68f8d6b2fd9ada6e041
1 ==========================
2 Using newforms 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.newforms 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.newforms.ModelChoiceField``,
90       which is a ``ChoiceField`` whose choices are a model ``QuerySet``.
92     * ``ManyToManyField`` is represented by
93       ``django.newforms.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
125     TITLE_CHOICES = (
126         ('MR', 'Mr.'),
127         ('MRS', 'Mrs.'),
128         ('MS', 'Ms.'),
129     )
131     class Author(models.Model):
132         name = models.CharField(max_length=100)
133         title = models.CharField(max_length=3, choices=TITLE_CHOICES)
134         birth_date = models.DateField(blank=True, null=True)
136         def __unicode__(self):
137             return self.name
139     class Book(models.Model):
140         name = models.CharField(max_length=100)
141         authors = models.ManyToManyField(Author)
143     class AuthorForm(ModelForm):
144         class Meta:
145             model = Author
147     class BookForm(ModelForm):
148         class Meta:
149             model = Book
151 With these models, the ``ModelForm`` subclasses above would be roughly
152 equivalent to this (the only difference being the ``save()`` method, which
153 we'll discuss in a moment.)::
155     class AuthorForm(forms.Form):
156         name = forms.CharField(max_length=100)
157         title = forms.CharField(max_length=3,
158                     widget=forms.Select(choices=TITLE_CHOICES))
159         birth_date = forms.DateField(required=False)
161     class BookForm(forms.Form):
162         name = forms.CharField(max_length=100)
163         authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all())
165 The ``save()`` method
166 ---------------------
168 Every form produced by ``ModelForm`` also has a ``save()``
169 method. This method creates and saves a database object from the data
170 bound to the form. A subclass of ``ModelForm`` can accept an existing
171 model instance as the keyword argument ``instance``; if this is
172 supplied, ``save()`` will update that instance. If it's not supplied,
173 ``save()`` will create a new instance of the specified model::
175     # Create a form instance from POST data.
176     >>> f = ArticleForm(request.POST)
178     # Save a new Article object from the form's data.
179     >>> new_article = f.save()
181     # Create a form to edit an existing Article.
182     >>> a = Article.objects.get(pk=1)
183     >>> f = ArticleForm(instance=a)
185 Note that ``save()`` will raise a ``ValueError`` if the data in the form
186 doesn't validate -- i.e., ``if form.errors``.
188 This ``save()`` method accepts an optional ``commit`` keyword argument, which
189 accepts either ``True`` or ``False``. If you call ``save()`` with
190 ``commit=False``, then it will return an object that hasn't yet been saved to
191 the database. In this case, it's up to you to call ``save()`` on the resulting
192 model instance. This is useful if you want to do custom processing on the
193 object before saving it. ``commit`` is ``True`` by default.
195 Another side effect of using ``commit=False`` is seen when your model has
196 a many-to-many relation with another model. If your model has a many-to-many
197 relation and you specify ``commit=False`` when you save a form, Django cannot
198 immediately save the form data for the many-to-many relation. This is because
199 it isn't possible to save many-to-many data for an instance until the instance
200 exists in the database.
202 To work around this problem, every time you save a form using ``commit=False``,
203 Django adds a ``save_m2m()`` method to your ``ModelForm`` subclass. After
204 you've manually saved the instance produced by the form, you can invoke
205 ``save_m2m()`` to save the many-to-many form data. For example::
207     # Create a form instance with POST data.
208     >>> f = AuthorForm(request.POST)
210     # Create, but don't save the new author instance.
211     >>> new_author = f.save(commit=False)
213     # Modify the author in some way.
214     >>> new_author.some_field = 'some_value'
216     # Save the new instance.
217     >>> new_author.save()
219     # Now, save the many-to-many data for the form.
220     >>> f.save_m2m()
222 Calling ``save_m2m()`` is only required if you use ``save(commit=False)``.
223 When you use a simple ``save()`` on a form, all data -- including
224 many-to-many data -- is saved without the need for any additional method calls.
225 For example::
227     # Create a form instance with POST data.
228     >>> a = Author()
229     >>> f = AuthorForm(request.POST, instance=a)
231     # Create and save the new author instance. There's no need to do anything else.
232     >>> new_author = f.save()
234 Using a subset of fields on the form
235 ------------------------------------
237 In some cases, you may not want all the model fields to appear on the generated
238 form. There are three ways of telling ``ModelForm`` to use only a subset of the
239 model fields:
241 1. Set ``editable=False`` on the model field. As a result, *any* form
242    created from the model via ``ModelForm`` will not include that
243    field.
245 2. Use the ``fields`` attribute of the ``ModelForm``'s inner ``Meta``
246    class.  This attribute, if given, should be a list of field names
247    to include in the form.
249 3. Use the ``exclude`` attribute of the ``ModelForm``'s inner ``Meta``
250    class.  This attribute, if given, should be a list of field names
251    to exclude the form.
253 For example, if you want a form for the ``Author`` model (defined
254 above) that includes only the ``name`` and ``title`` fields, you would
255 specify ``fields`` or ``exclude`` like this::
257     class PartialAuthorForm(ModelForm):
258         class Meta:
259             model = Author
260             fields = ('name', 'title')
261     
262     class PartialAuthorForm(ModelForm):
263         class Meta:
264             model = Author
265             exclude = ('birth_date',)
267 Since the Author model has only 3 fields, 'name', 'title', and
268 'birth_date', the forms above will contain exactly the same fields.
270 .. note::
272     If you specify ``fields`` or ``exclude`` when creating a form with
273     ``ModelForm``, then the fields that are not in the resulting form will not
274     be set by the form's ``save()`` method. Django will prevent any attempt to
275     save an incomplete model, so if the model does not allow the missing fields
276     to be empty, and does not provide a default value for the missing fields,
277     any attempt to ``save()`` a ``ModelForm`` with missing fields will fail.
278     To avoid this failure, you must instantiate your model with initial values
279     for the missing, but required fields, or use ``save(commit=False)`` and
280     manually set any extra required fields::
282         instance = Instance(required_field='value')
283         form = InstanceForm(request.POST, instance=instance)
284         new_instance = form.save()
286         instance = form.save(commit=False)
287         instance.required_field = 'new value'
288         new_instance = instance.save()
290     See the `section on saving forms`_ for more details on using
291     ``save(commit=False)``.
293 .. _section on saving forms: `The save() method`_
295 Overriding the default field types
296 ----------------------------------
298 The default field types, as described in the `Field types`_ table above, are
299 sensible defaults. If you have a ``DateField`` in your model, chances are you'd
300 want that to be represented as a ``DateField`` in your form. But
301 ``ModelForm`` gives you the flexibility of changing the form field type
302 for a given model field. You do this by declaratively specifying fields like
303 you would in a regular ``Form``. Declared fields will override the default
304 ones generated by using the ``model`` attribute.
306 For example, if you wanted to use ``MyDateFormField`` for the ``pub_date``
307 field, you could do the following::
309     >>> class ArticleForm(ModelForm):
310     ...     pub_date = MyDateFormField()
311     ...
312     ...     class Meta:
313     ...         model = Article
315 If you want to override a field's default widget, then specify the ``widget``
316 parameter when declaring the form field::
318    >>> class ArticleForm(ModelForm):
319    ...     pub_date = DateField(widget=MyDateWidget())
320    ...
321    ...     class Meta:
322    ...         model = Article
324 Form inheritance
325 ----------------
327 As with basic forms, you can extend and reuse ``ModelForms`` by inheriting
328 them. This is useful if you need to declare extra fields or extra methods on a
329 parent class for use in a number of forms derived from models. For example,
330 using the previous ``ArticleForm`` class::
332     >>> class EnhancedArticleForm(ArticleForm):
333     ...     def clean_pub_date(self):
334     ...         ...
336 This creates a form that behaves identically to ``ArticleForm``, except there's
337 some extra validation and cleaning for the ``pub_date`` field.
339 You can also subclass the parent's ``Meta`` inner class if you want to change
340 the ``Meta.fields`` or ``Meta.excludes`` lists::
342     >>> class RestrictedArticleForm(EnhancedArticleForm):
343     ...     class Meta(ArticleForm.Meta):
344     ...         exclude = ['body']
346 This adds the extra method from the ``EnhancedArticleForm`` and modifies
347 the original ``ArticleForm.Meta`` to remove one field.
349 There are a couple of things to note, however.
351  * Normal Python name resolution rules apply. If you have multiple base
352    classes that declare a ``Meta`` inner class, only the first one will be
353    used. This means the child's ``Meta``, if it exists, otherwise the
354    ``Meta`` of the first parent, etc.
356  * For technical reasons, a subclass cannot inherit from both a ``ModelForm``
357    and a ``Form`` simultaneously.
359 Chances are these notes won't affect you unless you're trying to do something
360 tricky with subclassing.