~ubuntu-branches/ubuntu/quantal/python-django/quantal-security

« back to all changes in this revision

Viewing changes to docs/topics/forms/modelforms.txt

  • Committer: Bazaar Package Importer
  • Author(s): Chris Lamb
  • Date: 2010-05-21 07:52:55 UTC
  • mfrom: (1.3.6 upstream)
  • mto: This revision was merged to the branch mainline in revision 28.
  • Revision ID: james.westby@ubuntu.com-20100521075255-ii78v1dyfmyu3uzx
Tags: upstream-1.2
ImportĀ upstreamĀ versionĀ 1.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
46
46
    ===============================  ========================================
47
47
    ``AutoField``                    Not represented in the form
48
48
 
 
49
    ``BigIntegerField``              ``IntegerField`` with ``min_value`` set
 
50
                                     to -9223372036854775808 and ``max_value``
 
51
                                     set to 9223372036854775807.
 
52
 
49
53
    ``BooleanField``                 ``BooleanField``
50
54
 
51
55
    ``CharField``                    ``CharField`` with ``max_length`` set to
108
112
    The ``FloatField`` form field and ``DecimalField`` model and form fields
109
113
    are new in Django 1.0.
110
114
 
 
115
.. versionadded:: 1.2
 
116
    The ``BigIntegerField`` is new in Django 1.2.
 
117
 
 
118
 
111
119
As you might expect, the ``ForeignKey`` and ``ManyToManyField`` model field
112
120
types are special cases:
113
121
 
138
146
      ``default`` value will be initially selected instead).
139
147
 
140
148
Finally, note that you can override the form field used for a given model
141
 
field. See `Overriding the default field types`_ below.
 
149
field. See `Overriding the default field types or widgets`_ below.
142
150
 
143
151
A full example
144
152
--------------
188
196
        name = forms.CharField(max_length=100)
189
197
        authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all())
190
198
 
 
199
The ``is_valid()`` method and ``errors``
 
200
----------------------------------------
 
201
 
 
202
.. versionchanged:: 1.2
 
203
 
 
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.
 
210
 
 
211
 
191
212
The ``save()`` method
192
213
---------------------
193
214
 
342
363
 
343
364
.. _section on saving forms: `The save() method`_
344
365
 
345
 
Overriding the default field types
346
 
----------------------------------
 
366
Overriding the default field types or widgets
 
367
---------------------------------------------
 
368
 
 
369
.. versionadded:: 1.2
 
370
        The ``widgets`` attribute is new in Django 1.2.
347
371
 
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.
 
377
 
 
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.
 
381
 
 
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
 
385
widget::
 
386
 
 
387
    from django.forms import ModelForm, Textarea
 
388
 
 
389
    class AuthorForm(ModelForm):
 
390
        class Meta:
 
391
            model = Author
 
392
            fields = ['name', 'title', 'birth_date']
 
393
            widgets = {
 
394
                'name': Textarea(attrs={'cols': 80, 'rows': 20}),
 
395
            }
 
396
 
 
397
The ``widgets`` dictionary accepts either widget instances (e.g.,
 
398
``Textarea(...)``) or classes (e.g., ``Textarea``).
 
399
 
 
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
 
403
``model`` attribute.
355
404
 
356
405
For example, if you wanted to use ``MyDateFormField`` for the ``pub_date``
357
406
field, you could do the following::
358
407
 
359
 
    >>> class ArticleForm(ModelForm):
360
 
    ...     pub_date = MyDateFormField()
361
 
    ...
362
 
    ...     class Meta:
363
 
    ...         model = Article
364
 
 
365
 
If you want to override a field's default widget, then specify the ``widget``
 
408
    class ArticleForm(ModelForm):
 
409
        pub_date = MyDateFormField()
 
410
 
 
411
        class Meta:
 
412
            model = Article
 
413
 
 
414
If you want to override a field's default label, then specify the ``label``
366
415
parameter when declaring the form field::
367
416
 
368
417
   >>> class ArticleForm(ModelForm):
369
 
   ...     pub_date = DateField(widget=MyDateWidget())
 
418
   ...     pub_date = DateField(label='Publication date')
370
419
   ...
371
420
   ...     class Meta:
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.
487
536
 
 
537
Interaction with model validation
 
538
---------------------------------
 
539
 
 
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.
 
548
 
488
549
.. _model-formsets:
489
550
 
490
551
Model formsets
502
563
 
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
---------------------------------------
600
661
 
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
 
663
 
 
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.
 
666
 
 
667
``max_num`` does not prevent existing objects from being displayed::
605
668
 
606
669
    >>> Author.objects.order_by('name')
607
670
    [<Author: Charles Baudelaire>, <Author: Paul Verlaine>, <Author: Walt Whitman>]
608
671
 
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'))
611
 
    >>> formset.initial
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']
613
676
 
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``::
617
680
 
618
681
    >>> AuthorFormSet = modelformset_factory(Author, max_num=4, extra=2)
619
682
    >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
624
687
    <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>
625
688
    <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>
626
689
 
 
690
.. versionchanged:: 1.2
 
691
 
 
692
A ``max_num`` value of ``None`` (the default) puts no limit on the number of
 
693
forms displayed.
 
694
 
627
695
Using a model formset in a view
628
696
-------------------------------
629
697
 
697
765
 
698
766
First, you can let the formset do most of the work::
699
767
 
700
 
    <form method="POST" action="">
 
768
    <form method="post" action="">
701
769
        {{ formset }}
702
770
    </form>
703
771
 
704
772
Second, you can manually render the formset, but let the form deal with
705
773
itself::
706
774
 
707
 
    <form method="POST" action="">
 
775
    <form method="post" action="">
708
776
        {{ formset.management_form }}
709
777
        {% for form in formset.forms %}
710
778
            {{ form }}
717
785
 
718
786
Third, you can manually render each field::
719
787
 
720
 
    <form method="POST" action="">
 
788
    <form method="post" action="">
721
789
        {{ formset.management_form }}
722
790
        {% for form in formset.forms %}
723
791
            {% for field in form %}
730
798
a ``{% for %}`` loop, you'll need to render the primary key field. For example,
731
799
if you were rendering the ``name`` and ``age`` fields of a model::
732
800
 
733
 
    <form method="POST" action="">
 
801
    <form method="post" action="">
734
802
        {{ formset.management_form }}
735
803
        {% for form in formset.forms %}
736
804
            {{ form.id }}