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