1 ==========================
2 Using newforms with models
3 ==========================
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.
19 >>> from django.newforms import ModelForm
21 # Create the form class.
22 >>> class ArticleForm(ModelForm):
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)
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
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 =============================== ========================================
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
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.
121 Consider this set of models::
123 from django.db import models
124 from django.newforms import ModelForm
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):
140 class Book(models.Model):
141 name = models.CharField(max_length=100)
142 authors = models.ManyToManyField(Author)
144 class AuthorForm(ModelForm):
148 class BookForm(ModelForm):
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)
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)
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.
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.
235 # Create a form instance with POST data.
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 ``newforms`` 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 newforms documentation`_
248 for more information.
250 .. _the standard newforms documentation: ../newforms/
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
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
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):
278 fields = ('name', 'title')
280 class PartialAuthorForm(ModelForm):
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.
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()
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())
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):
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.