46
46
=============================== ========================================
47
47
``AutoField`` Not represented in the form
49
``BigIntegerField`` ``IntegerField`` with ``min_value`` set
50
to -9223372036854775808 and ``max_value``
51
set to 9223372036854775807.
49
53
``BooleanField`` ``BooleanField``
51
55
``CharField`` ``CharField`` with ``max_length`` set to
188
196
name = forms.CharField(max_length=100)
189
197
authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all())
199
The ``is_valid()`` method and ``errors``
200
----------------------------------------
202
.. versionchanged:: 1.2
204
The first time you call ``is_valid()`` or access the ``errors`` attribute of a
205
``ModelForm`` has always triggered form validation, but as of Django 1.2, it
206
will also trigger :ref:`model validation <validating-objects>`. This has the
207
side-effect of cleaning the model you pass to the ``ModelForm`` constructor.
208
For instance, calling ``is_valid()`` on your form will convert any date fields
209
on your model to actual date objects.
191
212
The ``save()`` method
192
213
---------------------
343
364
.. _section on saving forms: `The save() method`_
345
Overriding the default field types
346
----------------------------------
366
Overriding the default field types or widgets
367
---------------------------------------------
369
.. versionadded:: 1.2
370
The ``widgets`` attribute is new in Django 1.2.
348
372
The default field types, as described in the `Field types`_ table above, are
349
373
sensible defaults. If you have a ``DateField`` in your model, chances are you'd
350
374
want that to be represented as a ``DateField`` in your form. But
351
``ModelForm`` gives you the flexibility of changing the form field type
352
for a given model field. You do this by declaratively specifying fields like
353
you would in a regular ``Form``. Declared fields will override the default
354
ones generated by using the ``model`` attribute.
375
``ModelForm`` gives you the flexibility of changing the form field type and
376
widget for a given model field.
378
To specify a custom widget for a field, use the ``widgets`` attribute of the
379
inner ``Meta`` class. This should be a dictionary mapping field names to widget
380
classes or instances.
382
For example, if you want the a ``CharField`` for the ``name``
383
attribute of ``Author`` to be represented by a ``<textarea>`` instead
384
of its default ``<input type="text">``, you can override the field's
387
from django.forms import ModelForm, Textarea
389
class AuthorForm(ModelForm):
392
fields = ['name', 'title', 'birth_date']
394
'name': Textarea(attrs={'cols': 80, 'rows': 20}),
397
The ``widgets`` dictionary accepts either widget instances (e.g.,
398
``Textarea(...)``) or classes (e.g., ``Textarea``).
400
If you want to further customize a field -- including its type, label, etc. --
401
you can do this by declaratively specifying fields like you would in a regular
402
``Form``. Declared fields will override the default ones generated by using the
356
405
For example, if you wanted to use ``MyDateFormField`` for the ``pub_date``
357
406
field, you could do the following::
359
>>> class ArticleForm(ModelForm):
360
... pub_date = MyDateFormField()
365
If you want to override a field's default widget, then specify the ``widget``
408
class ArticleForm(ModelForm):
409
pub_date = MyDateFormField()
414
If you want to override a field's default label, then specify the ``label``
366
415
parameter when declaring the form field::
368
417
>>> class ArticleForm(ModelForm):
369
... pub_date = DateField(widget=MyDateWidget())
418
... pub_date = DateField(label='Publication date')
372
421
... model = Article
485
534
Chances are these notes won't affect you unless you're trying to do something
486
535
tricky with subclassing.
537
Interaction with model validation
538
---------------------------------
540
As part of its validation process, ``ModelForm`` will call the ``clean()``
541
method of each field on your model that has a corresponding field on your form.
542
If you have excluded any model fields, validation will not be run on those
543
fields. See the :ref:`form validation <ref-forms-validation>` documentation
544
for more on how field cleaning and validation work. Also, your model's
545
``clean()`` method will be called before any uniqueness checks are made. See
546
:ref:`Validating objects <validating-objects>` for more information on the
547
model's ``clean()`` hook.
488
549
.. _model-formsets:
503
564
>>> formset = AuthorFormSet()
504
565
>>> print formset
505
<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" />
566
<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" />
506
567
<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>
507
568
<tr><th><label for="id_form-0-title">Title:</label></th><td><select name="form-0-title" id="id_form-0-title">
508
569
<option value="" selected="selected">---------</option>
598
659
Limiting the number of editable objects
599
660
---------------------------------------
601
As with regular formsets, you can use the ``max_num`` parameter to
602
``modelformset_factory`` to limit the number of forms displayed. With
603
model formsets, this property limits the query to select only the maximum
604
number of objects needed::
662
.. versionchanged:: 1.2
664
As with regular formsets, you can use the ``max_num`` and ``extra`` parameters
665
to ``modelformset_factory`` to limit the number of extra forms displayed.
667
``max_num`` does not prevent existing objects from being displayed::
606
669
>>> Author.objects.order_by('name')
607
670
[<Author: Charles Baudelaire>, <Author: Paul Verlaine>, <Author: Walt Whitman>]
609
>>> AuthorFormSet = modelformset_factory(Author, max_num=2, extra=1)
672
>>> AuthorFormSet = modelformset_factory(Author, max_num=1)
610
673
>>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
612
[{'id': 1, 'name': u'Charles Baudelaire'}, {'id': 3, 'name': u'Paul Verlaine'}]
674
>>> [x.name for x in formset.get_queryset()]
675
[u'Charles Baudelaire', u'Paul Verlaine', u'Walt Whitman']
614
If the value of ``max_num`` is higher than the number of objects returned, up to
615
``extra`` additional blank forms will be added to the formset, so long as the
616
total number of forms does not exceed ``max_num``::
677
If the value of ``max_num`` is greater than the number of existing related
678
objects, up to ``extra`` additional blank forms will be added to the formset,
679
so long as the total number of forms does not exceed ``max_num``::
618
681
>>> AuthorFormSet = modelformset_factory(Author, max_num=4, extra=2)
619
682
>>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
698
766
First, you can let the formset do most of the work::
700
<form method="POST" action="">
768
<form method="post" action="">
704
772
Second, you can manually render the formset, but let the form deal with
707
<form method="POST" action="">
775
<form method="post" action="">
708
776
{{ formset.management_form }}
709
777
{% for form in formset.forms %}