| 1 |
========================== |
| 2 |
Creating forms from models |
| 3 |
========================== |
| 4 |
|
| 5 |
.. currentmodule:: django.forms |
| 6 |
|
| 7 |
``ModelForm`` |
| 8 |
============= |
| 9 |
.. class:: ModelForm |
| 10 |
|
| 11 |
If you're building a database-driven app, chances are you'll have forms that |
| 12 |
map closely to Django models. For instance, you might have a ``BlogComment`` |
| 13 |
model, and you want to create a form that lets people submit comments. In this |
| 14 |
case, it would be redundant to define the field types in your form, because |
| 15 |
you've already defined the fields in your model. |
| 16 |
|
| 17 |
For this reason, Django provides a helper class that lets you create a ``Form`` |
| 18 |
class from a Django model. |
| 19 |
|
| 20 |
For example: |
| 21 |
|
| 22 |
.. code-block:: pycon |
| 23 |
|
| 24 |
>>> from django.forms import ModelForm |
| 25 |
>>> from myapp.models import Article |
| 26 |
|
| 27 |
# Create the form class. |
| 28 |
>>> class ArticleForm(ModelForm): |
| 29 |
... class Meta: |
| 30 |
... model = Article |
| 31 |
... fields = ["pub_date", "headline", "content", "reporter"] |
| 32 |
... |
| 33 |
|
| 34 |
# Creating a form to add an article. |
| 35 |
>>> form = ArticleForm() |
| 36 |
|
| 37 |
# Creating a form to change an existing article. |
| 38 |
>>> article = Article.objects.get(pk=1) |
| 39 |
>>> form = ArticleForm(instance=article) |
| 40 |
|
| 41 |
.. _model-form-field-types: |
| 42 |
|
| 43 |
Field types |
| 44 |
----------- |
| 45 |
|
| 46 |
The generated ``Form`` class will have a form field for every model field |
| 47 |
specified, in the order specified in the ``fields`` attribute. |
| 48 |
|
| 49 |
Each model field has a corresponding default form field. For example, a |
| 50 |
``CharField`` on a model is represented as a ``CharField`` on a form. A model |
| 51 |
``ManyToManyField`` is represented as a ``MultipleChoiceField``. Here is the |
| 52 |
full list of conversions: |
| 53 |
|
| 54 |
.. currentmodule:: django.db.models |
| 55 |
|
| 56 |
=================================== ================================================== |
| 57 |
Model field Form field |
| 58 |
=================================== ================================================== |
| 59 |
:class:`AutoField` Not represented in the form |
| 60 |
|
| 61 |
:class:`BigAutoField` Not represented in the form |
| 62 |
|
| 63 |
:class:`BigIntegerField` :class:`~django.forms.IntegerField` with |
| 64 |
``min_value`` set to -9223372036854775808 |
| 65 |
and ``max_value`` set to 9223372036854775807. |
| 66 |
|
| 67 |
:class:`BinaryField` :class:`~django.forms.CharField`, if |
| 68 |
:attr:`~.Field.editable` is set to |
| 69 |
``True`` on the model field, otherwise not |
| 70 |
represented in the form. |
| 71 |
|
| 72 |
:class:`BooleanField` :class:`~django.forms.BooleanField`, or |
| 73 |
:class:`~django.forms.NullBooleanField` if |
| 74 |
``null=True``. |
| 75 |
|
| 76 |
:class:`CharField` :class:`~django.forms.CharField` with |
| 77 |
``max_length`` set to the model field's |
| 78 |
``max_length`` and |
| 79 |
:attr:`~django.forms.CharField.empty_value` |
| 80 |
set to ``None`` if ``null=True``. |
| 81 |
|
| 82 |
:class:`DateField` :class:`~django.forms.DateField` |
| 83 |
|
| 84 |
:class:`DateTimeField` :class:`~django.forms.DateTimeField` |
| 85 |
|
| 86 |
:class:`DecimalField` :class:`~django.forms.DecimalField` |
| 87 |
|
| 88 |
:class:`DurationField` :class:`~django.forms.DurationField` |
| 89 |
|
| 90 |
:class:`EmailField` :class:`~django.forms.EmailField` |
| 91 |
|
| 92 |
:class:`FileField` :class:`~django.forms.FileField` |
| 93 |
|
| 94 |
:class:`FilePathField` :class:`~django.forms.FilePathField` |
| 95 |
|
| 96 |
:class:`FloatField` :class:`~django.forms.FloatField` |
| 97 |
|
| 98 |
:class:`ForeignKey` :class:`~django.forms.ModelChoiceField` |
| 99 |
(see below) |
| 100 |
|
| 101 |
:class:`ImageField` :class:`~django.forms.ImageField` |
| 102 |
|
| 103 |
:class:`IntegerField` :class:`~django.forms.IntegerField` |
| 104 |
|
| 105 |
``IPAddressField`` ``IPAddressField`` |
| 106 |
|
| 107 |
:class:`GenericIPAddressField` :class:`~django.forms.GenericIPAddressField` |
| 108 |
|
| 109 |
:class:`JSONField` :class:`~django.forms.JSONField` |
| 110 |
|
| 111 |
:class:`ManyToManyField` :class:`~django.forms.ModelMultipleChoiceField` |
| 112 |
(see below) |
| 113 |
|
| 114 |
:class:`PositiveBigIntegerField` :class:`~django.forms.IntegerField` |
| 115 |
|
| 116 |
:class:`PositiveIntegerField` :class:`~django.forms.IntegerField` |
| 117 |
|
| 118 |
:class:`PositiveSmallIntegerField` :class:`~django.forms.IntegerField` |
| 119 |
|
| 120 |
:class:`SlugField` :class:`~django.forms.SlugField` |
| 121 |
|
| 122 |
:class:`SmallAutoField` Not represented in the form |
| 123 |
|
| 124 |
:class:`SmallIntegerField` :class:`~django.forms.IntegerField` |
| 125 |
|
| 126 |
:class:`TextField` :class:`~django.forms.CharField` with |
| 127 |
``widget=forms.Textarea`` |
| 128 |
|
| 129 |
:class:`TimeField` :class:`~django.forms.TimeField` |
| 130 |
|
| 131 |
:class:`URLField` :class:`~django.forms.URLField` |
| 132 |
|
| 133 |
:class:`UUIDField` :class:`~django.forms.UUIDField` |
| 134 |
=================================== ================================================== |
| 135 |
|
| 136 |
.. currentmodule:: django.forms |
| 137 |
|
| 138 |
As you might expect, the ``ForeignKey`` and ``ManyToManyField`` model field |
| 139 |
types are special cases: |
| 140 |
|
| 141 |
* ``ForeignKey`` is represented by ``django.forms.ModelChoiceField``, |
| 142 |
which is a ``ChoiceField`` whose choices are a model ``QuerySet``. |
| 143 |
|
| 144 |
* ``ManyToManyField`` is represented by |
| 145 |
``django.forms.ModelMultipleChoiceField``, which is a |
| 146 |
``MultipleChoiceField`` whose choices are a model ``QuerySet``. |
| 147 |
|
| 148 |
In addition, each generated form field has attributes set as follows: |
| 149 |
|
| 150 |
* If the model field has ``blank=True``, then ``required`` is set to |
| 151 |
``False`` on the form field. Otherwise, ``required=True``. |
| 152 |
|
| 153 |
* The form field's ``label`` is set to the ``verbose_name`` of the model |
| 154 |
field, with the first character capitalized. |
| 155 |
|
| 156 |
* The form field's ``help_text`` is set to the ``help_text`` of the model |
| 157 |
field. |
| 158 |
|
| 159 |
* If the model field has ``choices`` set, then the form field's ``widget`` |
| 160 |
will be set to ``Select``, with choices coming from the model field's |
| 161 |
``choices``. The choices will normally include the blank choice which is |
| 162 |
selected by default. If the field is required, this forces the user to |
| 163 |
make a selection. The blank choice will not be included if the model |
| 164 |
field has ``blank=False`` and an explicit ``default`` value (the |
| 165 |
``default`` value will be initially selected instead). |
| 166 |
|
| 167 |
Finally, note that you can override the form field used for a given model |
| 168 |
field. See `Overriding the default fields`_ below. |
| 169 |
|
| 170 |
A full example |
| 171 |
-------------- |
| 172 |
|
| 173 |
Consider this set of models:: |
| 174 |
|
| 175 |
from django.db import models |
| 176 |
from django.forms import ModelForm |
| 177 |
|
| 178 |
TITLE_CHOICES = { |
| 179 |
"MR": "Mr.", |
| 180 |
"MRS": "Mrs.", |
| 181 |
"MS": "Ms.", |
| 182 |
} |
| 183 |
|
| 184 |
|
| 185 |
class Author(models.Model): |
| 186 |
name = models.CharField(max_length=100) |
| 187 |
title = models.CharField(max_length=3, choices=TITLE_CHOICES) |
| 188 |
birth_date = models.DateField(blank=True, null=True) |
| 189 |
|
| 190 |
def __str__(self): |
| 191 |
return self.name |
| 192 |
|
| 193 |
|
| 194 |
class Book(models.Model): |
| 195 |
name = models.CharField(max_length=100) |
| 196 |
authors = models.ManyToManyField(Author) |
| 197 |
|
| 198 |
|
| 199 |
class AuthorForm(ModelForm): |
| 200 |
class Meta: |
| 201 |
model = Author |
| 202 |
fields = ["name", "title", "birth_date"] |
| 203 |
|
| 204 |
|
| 205 |
class BookForm(ModelForm): |
| 206 |
class Meta: |
| 207 |
model = Book |
| 208 |
fields = ["name", "authors"] |
| 209 |
|
| 210 |
|
| 211 |
With these models, the ``ModelForm`` subclasses above would be roughly |
| 212 |
equivalent to this (the only difference being the ``save()`` method, which |
| 213 |
we'll discuss in a moment.):: |
| 214 |
|
| 215 |
from django import forms |
| 216 |
|
| 217 |
|
| 218 |
class AuthorForm(forms.Form): |
| 219 |
name = forms.CharField(max_length=100) |
| 220 |
title = forms.CharField( |
| 221 |
max_length=3, |
| 222 |
widget=forms.Select(choices=TITLE_CHOICES), |
| 223 |
) |
| 224 |
birth_date = forms.DateField(required=False) |
| 225 |
|
| 226 |
|
| 227 |
class BookForm(forms.Form): |
| 228 |
name = forms.CharField(max_length=100) |
| 229 |
authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all()) |
| 230 |
|
| 231 |
.. _validation-on-modelform: |
| 232 |
|
| 233 |
Validation on a ``ModelForm`` |
| 234 |
----------------------------- |
| 235 |
|
| 236 |
There are two main steps involved in validating a ``ModelForm``: |
| 237 |
|
| 238 |
1. :doc:`Validating the form </ref/forms/validation>` |
| 239 |
2. :ref:`Validating the model instance <validating-objects>` |
| 240 |
|
| 241 |
Just like normal form validation, model form validation is triggered implicitly |
| 242 |
when calling :meth:`~django.forms.Form.is_valid()` or accessing the |
| 243 |
:attr:`~django.forms.Form.errors` attribute and explicitly when calling |
| 244 |
``full_clean()``, although you will typically not use the latter method in |
| 245 |
practice. |
| 246 |
|
| 247 |
``Model`` validation (:meth:`Model.full_clean() |
| 248 |
<django.db.models.Model.full_clean()>`) is triggered from within the form |
| 249 |
validation step, right after the form's ``clean()`` method is called. |
| 250 |
|
| 251 |
.. warning:: |
| 252 |
|
| 253 |
The cleaning process modifies the model instance passed to the |
| 254 |
``ModelForm`` constructor in various ways. For instance, any date fields on |
| 255 |
the model are converted into actual date objects. Failed validation may |
| 256 |
leave the underlying model instance in an inconsistent state and therefore |
| 257 |
it's not recommended to reuse it. |
| 258 |
|
| 259 |
.. _overriding-modelform-clean-method: |
| 260 |
|
| 261 |
Overriding the ``clean()`` method |
| 262 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 263 |
|
| 264 |
You can override the ``clean()`` method on a model form to provide additional |
| 265 |
validation in the same way you can on a normal form. |
| 266 |
|
| 267 |
A model form instance attached to a model object will contain an ``instance`` |
| 268 |
attribute that gives its methods access to that specific model instance. |
| 269 |
|
| 270 |
.. warning:: |
| 271 |
|
| 272 |
The ``ModelForm.clean()`` method sets a flag that makes the :ref:`model |
| 273 |
validation <validating-objects>` step validate the uniqueness of model |
| 274 |
fields that are marked as ``unique``, ``unique_together`` or |
| 275 |
``unique_for_date|month|year``. |
| 276 |
|
| 277 |
If you would like to override the ``clean()`` method and maintain this |
| 278 |
validation, you must call the parent class's ``clean()`` method. |
| 279 |
|
| 280 |
Interaction with model validation |
| 281 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 282 |
|
| 283 |
As part of the validation process, ``ModelForm`` will call the ``clean()`` |
| 284 |
method of each field on your model that has a corresponding field on your form. |
| 285 |
If you have excluded any model fields, validation will not be run on those |
| 286 |
fields. See the :doc:`form validation </ref/forms/validation>` documentation |
| 287 |
for more on how field cleaning and validation work. |
| 288 |
|
| 289 |
The model's ``clean()`` method will be called before any uniqueness checks are |
| 290 |
made. See :ref:`Validating objects <validating-objects>` for more information |
| 291 |
on the model's ``clean()`` hook. |
| 292 |
|
| 293 |
.. _considerations-regarding-model-errormessages: |
| 294 |
|
| 295 |
Considerations regarding model's ``error_messages`` |
| 296 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 297 |
|
| 298 |
Error messages defined at the |
| 299 |
:attr:`form field <django.forms.Field.error_messages>` level or at the |
| 300 |
:ref:`form Meta <modelforms-overriding-default-fields>` level always take |
| 301 |
precedence over the error messages defined at the |
| 302 |
:attr:`model field <django.db.models.Field.error_messages>` level. |
| 303 |
|
| 304 |
Error messages defined on :attr:`model fields |
| 305 |
<django.db.models.Field.error_messages>` are only used when the |
| 306 |
``ValidationError`` is raised during the :ref:`model validation |
| 307 |
<validating-objects>` step and no corresponding error messages are defined at |
| 308 |
the form level. |
| 309 |
|
| 310 |
You can override the error messages from ``NON_FIELD_ERRORS`` raised by model |
| 311 |
validation by adding the :data:`~django.core.exceptions.NON_FIELD_ERRORS` key |
| 312 |
to the ``error_messages`` dictionary of the ``ModelForm``’s inner ``Meta`` class:: |
| 313 |
|
| 314 |
from django.core.exceptions import NON_FIELD_ERRORS |
| 315 |
from django.forms import ModelForm |
| 316 |
|
| 317 |
|
| 318 |
class ArticleForm(ModelForm): |
| 319 |
class Meta: |
| 320 |
error_messages = { |
| 321 |
NON_FIELD_ERRORS: { |
| 322 |
"unique_together": "%(model_name)s's %(field_labels)s are not unique.", |
| 323 |
} |
| 324 |
} |
| 325 |
|
| 326 |
.. _topics-modelform-save: |
| 327 |
|
| 328 |
The ``save()`` method |
| 329 |
--------------------- |
| 330 |
|
| 331 |
Every ``ModelForm`` also has a ``save()`` method. This method creates and saves |
| 332 |
a database object from the data bound to the form. A subclass of ``ModelForm`` |
| 333 |
can accept an existing model instance as the keyword argument ``instance``; if |
| 334 |
this is supplied, ``save()`` will update that instance. If it's not supplied, |
| 335 |
``save()`` will create a new instance of the specified model: |
| 336 |
|
| 337 |
.. code-block:: pycon |
| 338 |
|
| 339 |
>>> from myapp.models import Article |
| 340 |
>>> from myapp.forms import ArticleForm |
| 341 |
|
| 342 |
# Create a form instance from POST data. |
| 343 |
>>> f = ArticleForm(request.POST) |
| 344 |
|
| 345 |
# Save a new Article object from the form's data. |
| 346 |
>>> new_article = f.save() |
| 347 |
|
| 348 |
# Create a form to edit an existing Article, but use |
| 349 |
# POST data to populate the form. |
| 350 |
>>> a = Article.objects.get(pk=1) |
| 351 |
>>> f = ArticleForm(request.POST, instance=a) |
| 352 |
>>> f.save() |
| 353 |
|
| 354 |
Note that if the form :ref:`hasn't been validated |
| 355 |
<validation-on-modelform>`, calling ``save()`` will do so by checking |
| 356 |
``form.errors``. A ``ValueError`` will be raised if the data in the form |
| 357 |
doesn't validate -- i.e., if ``form.errors`` evaluates to ``True``. |
| 358 |
|
| 359 |
If an optional field doesn't appear in the form's data, the resulting model |
| 360 |
instance uses the model field :attr:`~django.db.models.Field.default`, if |
| 361 |
there is one, for that field. This behavior doesn't apply to fields that use |
| 362 |
:class:`~django.forms.CheckboxInput`, |
| 363 |
:class:`~django.forms.CheckboxSelectMultiple`, or |
| 364 |
:class:`~django.forms.SelectMultiple` (or any custom widget whose |
| 365 |
:meth:`~django.forms.Widget.value_omitted_from_data` method always returns |
| 366 |
``False``) since an unchecked checkbox and unselected ``<select multiple>`` |
| 367 |
don't appear in the data of an HTML form submission. Use a custom form field or |
| 368 |
widget if you're designing an API and want the default fallback behavior for a |
| 369 |
field that uses one of these widgets. |
| 370 |
|
| 371 |
This ``save()`` method accepts an optional ``commit`` keyword argument, which |
| 372 |
accepts either ``True`` or ``False``. If you call ``save()`` with |
| 373 |
``commit=False``, then it will return an object that hasn't yet been saved to |
| 374 |
the database. In this case, it's up to you to call ``save()`` on the resulting |
| 375 |
model instance. This is useful if you want to do custom processing on the |
| 376 |
object before saving it, or if you want to use one of the specialized |
| 377 |
:ref:`model saving options <ref-models-force-insert>`. ``commit`` is ``True`` |
| 378 |
by default. |
| 379 |
|
| 380 |
Another side effect of using ``commit=False`` is seen when your model has |
| 381 |
a many-to-many relation with another model. If your model has a many-to-many |
| 382 |
relation and you specify ``commit=False`` when you save a form, Django cannot |
| 383 |
immediately save the form data for the many-to-many relation. This is because |
| 384 |
it isn't possible to save many-to-many data for an instance until the instance |
| 385 |
exists in the database. |
| 386 |
|
| 387 |
To work around this problem, every time you save a form using ``commit=False``, |
| 388 |
Django adds a ``save_m2m()`` method to your ``ModelForm`` subclass. After |
| 389 |
you've manually saved the instance produced by the form, you can invoke |
| 390 |
``save_m2m()`` to save the many-to-many form data. For example: |
| 391 |
|
| 392 |
.. code-block:: pycon |
| 393 |
|
| 394 |
# Create a form instance with POST data. |
| 395 |
>>> f = AuthorForm(request.POST) |
| 396 |
|
| 397 |
# Create, but don't save the new author instance. |
| 398 |
>>> new_author = f.save(commit=False) |
| 399 |
|
| 400 |
# Modify the author in some way. |
| 401 |
>>> new_author.some_field = "some_value" |
| 402 |
|
| 403 |
# Save the new instance. |
| 404 |
>>> new_author.save() |
| 405 |
|
| 406 |
# Now, save the many-to-many data for the form. |
| 407 |
>>> f.save_m2m() |
| 408 |
|
| 409 |
Calling ``save_m2m()`` is only required if you use ``save(commit=False)``. |
| 410 |
When you use a ``save()`` on a form, all data -- including many-to-many data -- |
| 411 |
is saved without the need for any additional method calls. For example: |
| 412 |
|
| 413 |
.. code-block:: pycon |
| 414 |
|
| 415 |
# Create a form instance with POST data. |
| 416 |
>>> a = Author() |
| 417 |
>>> f = AuthorForm(request.POST, instance=a) |
| 418 |
|
| 419 |
# Create and save the new author instance. There's no need to do anything else. |
| 420 |
>>> new_author = f.save() |
| 421 |
|
| 422 |
Other than the ``save()`` and ``save_m2m()`` methods, a ``ModelForm`` works |
| 423 |
exactly the same way as any other ``forms`` form. For example, the |
| 424 |
``is_valid()`` method is used to check for validity, the ``is_multipart()`` |
| 425 |
method is used to determine whether a form requires multipart file upload (and |
| 426 |
hence whether ``request.FILES`` must be passed to the form), etc. See |
| 427 |
:ref:`binding-uploaded-files` for more information. |
| 428 |
|
| 429 |
.. _modelforms-selecting-fields: |
| 430 |
|
| 431 |
Selecting the fields to use |
| 432 |
--------------------------- |
| 433 |
|
| 434 |
It is strongly recommended that you explicitly set all fields that should be |
| 435 |
edited in the form using the ``fields`` attribute. Failure to do so can easily |
| 436 |
lead to security problems when a form unexpectedly allows a user to set certain |
| 437 |
fields, especially when new fields are added to a model. Depending on how the |
| 438 |
form is rendered, the problem may not even be visible on the web page. |
| 439 |
|
| 440 |
The alternative approach would be to include all fields automatically, or |
| 441 |
remove only some. This fundamental approach is known to be much less secure |
| 442 |
and has led to serious exploits on major websites (e.g. `GitHub |
| 443 |
<https://github.blog/2012-03-04-public-key-security-vulnerability-and-mitigation/>`_). |
| 444 |
|
| 445 |
There are, however, two shortcuts available for cases where you can guarantee |
| 446 |
these security concerns do not apply to you: |
| 447 |
|
| 448 |
1. Set the ``fields`` attribute to the special value ``'__all__'`` to indicate |
| 449 |
that all fields in the model should be used. For example:: |
| 450 |
|
| 451 |
from django.forms import ModelForm |
| 452 |
|
| 453 |
|
| 454 |
class AuthorForm(ModelForm): |
| 455 |
class Meta: |
| 456 |
model = Author |
| 457 |
fields = "__all__" |
| 458 |
|
| 459 |
2. Set the ``exclude`` attribute of the ``ModelForm``’s inner ``Meta`` class to |
| 460 |
a list of fields to be excluded from the form. |
| 461 |
|
| 462 |
For example:: |
| 463 |
|
| 464 |
class PartialAuthorForm(ModelForm): |
| 465 |
class Meta: |
| 466 |
model = Author |
| 467 |
exclude = ["title"] |
| 468 |
|
| 469 |
Since the ``Author`` model has the 3 fields ``name``, ``title`` and |
| 470 |
``birth_date``, this will result in the fields ``name`` and ``birth_date`` |
| 471 |
being present on the form. |
| 472 |
|
| 473 |
If either of these are used, the order the fields appear in the form will be the |
| 474 |
order the fields are defined in the model, with ``ManyToManyField`` instances |
| 475 |
appearing last. |
| 476 |
|
| 477 |
In addition, Django applies the following rule: if you set ``editable=False`` on |
| 478 |
the model field, *any* form created from the model via ``ModelForm`` will not |
| 479 |
include that field. |
| 480 |
|
| 481 |
.. note:: |
| 482 |
|
| 483 |
Any fields not included in a form by the above logic |
| 484 |
will not be set by the form's ``save()`` method. Also, if you |
| 485 |
manually add the excluded fields back to the form, they will not |
| 486 |
be initialized from the model instance. |
| 487 |
|
| 488 |
Django will prevent any attempt to save an incomplete model, so if |
| 489 |
the model does not allow the missing fields to be empty, and does |
| 490 |
not provide a default value for the missing fields, any attempt to |
| 491 |
``save()`` a ``ModelForm`` with missing fields will fail. To |
| 492 |
avoid this failure, you must instantiate your model with initial |
| 493 |
values for the missing, but required fields:: |
| 494 |
|
| 495 |
author = Author(title="Mr") |
| 496 |
form = PartialAuthorForm(request.POST, instance=author) |
| 497 |
form.save() |
| 498 |
|
| 499 |
Alternatively, you can use ``save(commit=False)`` and manually set |
| 500 |
any extra required fields:: |
| 501 |
|
| 502 |
form = PartialAuthorForm(request.POST) |
| 503 |
author = form.save(commit=False) |
| 504 |
author.title = "Mr" |
| 505 |
author.save() |
| 506 |
|
| 507 |
See the `section on saving forms`_ for more details on using |
| 508 |
``save(commit=False)``. |
| 509 |
|
| 510 |
.. _section on saving forms: `The save() method`_ |
| 511 |
|
| 512 |
.. _modelforms-overriding-default-fields: |
| 513 |
|
| 514 |
Overriding the default fields |
| 515 |
----------------------------- |
| 516 |
|
| 517 |
The default field types, as described in the `Field types`_ table above, are |
| 518 |
sensible defaults. If you have a ``DateField`` in your model, chances are you'd |
| 519 |
want that to be represented as a ``DateField`` in your form. But ``ModelForm`` |
| 520 |
gives you the flexibility of changing the form field for a given model. |
| 521 |
|
| 522 |
To specify a custom widget for a field, use the ``widgets`` attribute of the |
| 523 |
inner ``Meta`` class. This should be a dictionary mapping field names to widget |
| 524 |
classes or instances. |
| 525 |
|
| 526 |
For example, if you want the ``CharField`` for the ``name`` attribute of |
| 527 |
``Author`` to be represented by a ``<textarea>`` instead of its default |
| 528 |
``<input type="text">``, you can override the field's widget:: |
| 529 |
|
| 530 |
from django.forms import ModelForm, Textarea |
| 531 |
from myapp.models import Author |
| 532 |
|
| 533 |
|
| 534 |
class AuthorForm(ModelForm): |
| 535 |
class Meta: |
| 536 |
model = Author |
| 537 |
fields = ["name", "title", "birth_date"] |
| 538 |
widgets = { |
| 539 |
"name": Textarea(attrs={"cols": 80, "rows": 20}), |
| 540 |
} |
| 541 |
|
| 542 |
The ``widgets`` dictionary accepts either widget instances (e.g., |
| 543 |
``Textarea(...)``) or classes (e.g., ``Textarea``). Note that the ``widgets`` |
| 544 |
dictionary is ignored for a model field with a non-empty ``choices`` attribute. |
| 545 |
In this case, you must override the form field to use a different widget. |
| 546 |
|
| 547 |
Similarly, you can specify the ``labels``, ``help_texts`` and ``error_messages`` |
| 548 |
attributes of the inner ``Meta`` class if you want to further customize a field. |
| 549 |
|
| 550 |
For example if you wanted to customize the wording of all user facing strings for |
| 551 |
the ``name`` field:: |
| 552 |
|
| 553 |
from django.utils.translation import gettext_lazy as _ |
| 554 |
|
| 555 |
|
| 556 |
class AuthorForm(ModelForm): |
| 557 |
class Meta: |
| 558 |
model = Author |
| 559 |
fields = ["name", "title", "birth_date"] |
| 560 |
labels = { |
| 561 |
"name": _("Writer"), |
| 562 |
} |
| 563 |
help_texts = { |
| 564 |
"name": _("Some useful help text."), |
| 565 |
} |
| 566 |
error_messages = { |
| 567 |
"name": { |
| 568 |
"max_length": _("This writer's name is too long."), |
| 569 |
}, |
| 570 |
} |
| 571 |
|
| 572 |
You can also specify ``field_classes`` or ``formfield_callback`` to customize |
| 573 |
the type of fields instantiated by the form. |
| 574 |
|
| 575 |
For example, if you wanted to use ``MySlugFormField`` for the ``slug`` |
| 576 |
field, you could do the following:: |
| 577 |
|
| 578 |
from django.forms import ModelForm |
| 579 |
from myapp.models import Article |
| 580 |
|
| 581 |
|
| 582 |
class ArticleForm(ModelForm): |
| 583 |
class Meta: |
| 584 |
model = Article |
| 585 |
fields = ["pub_date", "headline", "content", "reporter", "slug"] |
| 586 |
field_classes = { |
| 587 |
"slug": MySlugFormField, |
| 588 |
} |
| 589 |
|
| 590 |
or:: |
| 591 |
|
| 592 |
from django.forms import ModelForm |
| 593 |
from myapp.models import Article |
| 594 |
|
| 595 |
|
| 596 |
def formfield_for_dbfield(db_field, **kwargs): |
| 597 |
if db_field.name == "slug": |
| 598 |
return MySlugFormField() |
| 599 |
return db_field.formfield(**kwargs) |
| 600 |
|
| 601 |
|
| 602 |
class ArticleForm(ModelForm): |
| 603 |
class Meta: |
| 604 |
model = Article |
| 605 |
fields = ["pub_date", "headline", "content", "reporter", "slug"] |
| 606 |
formfield_callback = formfield_for_dbfield |
| 607 |
|
| 608 |
Finally, if you want complete control over of a field -- including its type, |
| 609 |
validators, required, etc. -- you can do this by declaratively specifying |
| 610 |
fields like you would in a regular ``Form``. |
| 611 |
|
| 612 |
If you want to specify a field's validators, you can do so by defining |
| 613 |
the field declaratively and setting its ``validators`` parameter:: |
| 614 |
|
| 615 |
from django.forms import CharField, ModelForm |
| 616 |
from myapp.models import Article |
| 617 |
|
| 618 |
|
| 619 |
class ArticleForm(ModelForm): |
| 620 |
slug = CharField(validators=[validate_slug]) |
| 621 |
|
| 622 |
class Meta: |
| 623 |
model = Article |
| 624 |
fields = ["pub_date", "headline", "content", "reporter", "slug"] |
| 625 |
|
| 626 |
.. note:: |
| 627 |
|
| 628 |
When you explicitly instantiate a form field like this, it is important to |
| 629 |
understand how ``ModelForm`` and regular ``Form`` are related. |
| 630 |
|
| 631 |
``ModelForm`` is a regular ``Form`` which can automatically generate |
| 632 |
certain fields. The fields that are automatically generated depend on |
| 633 |
the content of the ``Meta`` class and on which fields have already been |
| 634 |
defined declaratively. Basically, ``ModelForm`` will **only** generate fields |
| 635 |
that are **missing** from the form, or in other words, fields that weren't |
| 636 |
defined declaratively. |
| 637 |
|
| 638 |
Fields defined declaratively are left as-is, therefore any customizations |
| 639 |
made to ``Meta`` attributes such as ``widgets``, ``labels``, ``help_texts``, |
| 640 |
or ``error_messages`` are ignored; these only apply to fields that are |
| 641 |
generated automatically. |
| 642 |
|
| 643 |
Similarly, fields defined declaratively do not draw their attributes like |
| 644 |
``max_length`` or ``required`` from the corresponding model. If you want to |
| 645 |
maintain the behavior specified in the model, you must set the relevant |
| 646 |
arguments explicitly when declaring the form field. |
| 647 |
|
| 648 |
For example, if the ``Article`` model looks like this:: |
| 649 |
|
| 650 |
class Article(models.Model): |
| 651 |
headline = models.CharField( |
| 652 |
max_length=200, |
| 653 |
null=True, |
| 654 |
blank=True, |
| 655 |
help_text="Use puns liberally", |
| 656 |
) |
| 657 |
content = models.TextField() |
| 658 |
|
| 659 |
and you want to do some custom validation for ``headline``, while keeping |
| 660 |
the ``blank`` and ``help_text`` values as specified, you might define |
| 661 |
``ArticleForm`` like this:: |
| 662 |
|
| 663 |
class ArticleForm(ModelForm): |
| 664 |
headline = MyFormField( |
| 665 |
max_length=200, |
| 666 |
required=False, |
| 667 |
help_text="Use puns liberally", |
| 668 |
) |
| 669 |
|
| 670 |
class Meta: |
| 671 |
model = Article |
| 672 |
fields = ["headline", "content"] |
| 673 |
|
| 674 |
You must ensure that the type of the form field can be used to set the |
| 675 |
contents of the corresponding model field. When they are not compatible, |
| 676 |
you will get a ``ValueError`` as no implicit conversion takes place. |
| 677 |
|
| 678 |
See the :doc:`form field documentation </ref/forms/fields>` for more information |
| 679 |
on fields and their arguments. |
| 680 |
|
| 681 |
.. _modelforms-enabling-localization-of-fields: |
| 682 |
|
| 683 |
Enabling localization of fields |
| 684 |
------------------------------- |
| 685 |
|
| 686 |
By default, the fields in a ``ModelForm`` will not localize their data. To |
| 687 |
enable localization for fields, you can use the ``localized_fields`` |
| 688 |
attribute on the ``Meta`` class. |
| 689 |
|
| 690 |
>>> from django.forms import ModelForm |
| 691 |
>>> from myapp.models import Author |
| 692 |
>>> class AuthorForm(ModelForm): |
| 693 |
... class Meta: |
| 694 |
... model = Author |
| 695 |
... localized_fields = ['birth_date'] |
| 696 |
|
| 697 |
If ``localized_fields`` is set to the special value ``'__all__'``, all fields |
| 698 |
will be localized. |
| 699 |
|
| 700 |
Form inheritance |
| 701 |
---------------- |
| 702 |
|
| 703 |
As with basic forms, you can extend and reuse ``ModelForm`` classes by |
| 704 |
inheriting them. This is useful if you need to declare extra fields or extra |
| 705 |
methods on a parent class for use in a number of forms derived from models. |
| 706 |
For example, using the previous ``ArticleForm`` class: |
| 707 |
|
| 708 |
.. code-block:: pycon |
| 709 |
|
| 710 |
>>> class EnhancedArticleForm(ArticleForm): |
| 711 |
... def clean_pub_date(self): ... |
| 712 |
... |
| 713 |
|
| 714 |
This creates a form that behaves identically to ``ArticleForm``, except there's |
| 715 |
some extra validation and cleaning for the ``pub_date`` field. |
| 716 |
|
| 717 |
You can also subclass the parent's ``Meta`` inner class if you want to change |
| 718 |
the ``Meta.fields`` or ``Meta.exclude`` lists: |
| 719 |
|
| 720 |
.. code-block:: pycon |
| 721 |
|
| 722 |
>>> class RestrictedArticleForm(EnhancedArticleForm): |
| 723 |
... class Meta(ArticleForm.Meta): |
| 724 |
... exclude = ["body"] |
| 725 |
... |
| 726 |
|
| 727 |
This adds the extra method from the ``EnhancedArticleForm`` and modifies |
| 728 |
the original ``ArticleForm.Meta`` to remove one field. |
| 729 |
|
| 730 |
There are a couple of things to note, however. |
| 731 |
|
| 732 |
* Normal Python name resolution rules apply. If you have multiple base |
| 733 |
classes that declare a ``Meta`` inner class, only the first one will be |
| 734 |
used. This means the child's ``Meta``, if it exists, otherwise the |
| 735 |
``Meta`` of the first parent, etc. |
| 736 |
|
| 737 |
* It's possible to inherit from both ``Form`` and ``ModelForm`` simultaneously, |
| 738 |
however, you must ensure that ``ModelForm`` appears first in the MRO. This is |
| 739 |
because these classes rely on different metaclasses and a class can only have |
| 740 |
one metaclass. |
| 741 |
|
| 742 |
* It's possible to declaratively remove a ``Field`` inherited from a parent class by |
| 743 |
setting the name to be ``None`` on the subclass. |
| 744 |
|
| 745 |
You can only use this technique to opt out from a field defined declaratively |
| 746 |
by a parent class; it won't prevent the ``ModelForm`` metaclass from generating |
| 747 |
a default field. To opt-out from default fields, see |
| 748 |
:ref:`modelforms-selecting-fields`. |
| 749 |
|
| 750 |
Providing initial values |
| 751 |
------------------------ |
| 752 |
|
| 753 |
As with regular forms, it's possible to specify initial data for forms by |
| 754 |
specifying an ``initial`` parameter when instantiating the form. Initial |
| 755 |
values provided this way will override both initial values from the form field |
| 756 |
and values from an attached model instance. For example: |
| 757 |
|
| 758 |
.. code-block:: pycon |
| 759 |
|
| 760 |
>>> article = Article.objects.get(pk=1) |
| 761 |
>>> article.headline |
| 762 |
'My headline' |
| 763 |
>>> form = ArticleForm(initial={"headline": "Initial headline"}, instance=article) |
| 764 |
>>> form["headline"].value() |
| 765 |
'Initial headline' |
| 766 |
|
| 767 |
.. _modelforms-factory: |
| 768 |
|
| 769 |
ModelForm factory function |
| 770 |
-------------------------- |
| 771 |
|
| 772 |
You can create forms from a given model using the standalone function |
| 773 |
:func:`~django.forms.models.modelform_factory`, instead of using a class |
| 774 |
definition. This may be more convenient if you do not have many customizations |
| 775 |
to make: |
| 776 |
|
| 777 |
.. code-block:: pycon |
| 778 |
|
| 779 |
>>> from django.forms import modelform_factory |
| 780 |
>>> from myapp.models import Book |
| 781 |
>>> BookForm = modelform_factory(Book, fields=["author", "title"]) |
| 782 |
|
| 783 |
This can also be used to make modifications to existing forms, for example by |
| 784 |
specifying the widgets to be used for a given field: |
| 785 |
|
| 786 |
.. code-block:: pycon |
| 787 |
|
| 788 |
>>> from django.forms import Textarea |
| 789 |
>>> Form = modelform_factory(Book, form=BookForm, widgets={"title": Textarea()}) |
| 790 |
|
| 791 |
The fields to include can be specified using the ``fields`` and ``exclude`` |
| 792 |
keyword arguments, or the corresponding attributes on the ``ModelForm`` inner |
| 793 |
``Meta`` class. Please see the ``ModelForm`` :ref:`modelforms-selecting-fields` |
| 794 |
documentation. |
| 795 |
|
| 796 |
... or enable localization for specific fields: |
| 797 |
|
| 798 |
.. code-block:: pycon |
| 799 |
|
| 800 |
>>> Form = modelform_factory(Author, form=AuthorForm, localized_fields=["birth_date"]) |
| 801 |
|
| 802 |
.. _model-formsets: |
| 803 |
|
| 804 |
Model formsets |
| 805 |
============== |
| 806 |
|
| 807 |
.. class:: models.BaseModelFormSet |
| 808 |
|
| 809 |
Like :doc:`regular formsets </topics/forms/formsets>`, Django provides a couple |
| 810 |
of enhanced formset classes to make working with Django models more |
| 811 |
convenient. Let's reuse the ``Author`` model from above: |
| 812 |
|
| 813 |
.. code-block:: pycon |
| 814 |
|
| 815 |
>>> from django.forms import modelformset_factory |
| 816 |
>>> from myapp.models import Author |
| 817 |
>>> AuthorFormSet = modelformset_factory(Author, fields=["name", "title"]) |
| 818 |
|
| 819 |
Using ``fields`` restricts the formset to use only the given fields. |
| 820 |
Alternatively, you can take an "opt-out" approach, specifying which fields to |
| 821 |
exclude: |
| 822 |
|
| 823 |
.. code-block:: pycon |
| 824 |
|
| 825 |
>>> AuthorFormSet = modelformset_factory(Author, exclude=["birth_date"]) |
| 826 |
|
| 827 |
This will create a formset that is capable of working with the data associated |
| 828 |
with the ``Author`` model. It works just like a regular formset: |
| 829 |
|
| 830 |
.. code-block:: pycon |
| 831 |
|
| 832 |
>>> formset = AuthorFormSet() |
| 833 |
>>> print(formset) |
| 834 |
<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-MIN_NUM_FORMS" value="0" id="id_form-MIN_NUM_FORMS"><input type="hidden" name="form-MAX_NUM_FORMS" value="1000" id="id_form-MAX_NUM_FORMS"> |
| 835 |
<div><label for="id_form-0-name">Name:</label><input id="id_form-0-name" type="text" name="form-0-name" maxlength="100"></div> |
| 836 |
<div><label for="id_form-0-title">Title:</label><select name="form-0-title" id="id_form-0-title"> |
| 837 |
<option value="" selected>---------</option> |
| 838 |
<option value="MR">Mr.</option> |
| 839 |
<option value="MRS">Mrs.</option> |
| 840 |
<option value="MS">Ms.</option> |
| 841 |
</select><input type="hidden" name="form-0-id" id="id_form-0-id"></div> |
| 842 |
|
| 843 |
.. note:: |
| 844 |
|
| 845 |
:func:`~django.forms.models.modelformset_factory` uses |
| 846 |
:func:`~django.forms.formsets.formset_factory` to generate formsets. This |
| 847 |
means that a model formset is an extension of a basic formset that knows |
| 848 |
how to interact with a particular model. |
| 849 |
|
| 850 |
.. note:: |
| 851 |
|
| 852 |
When using :ref:`multi-table inheritance <multi-table-inheritance>`, forms |
| 853 |
generated by a formset factory will contain a parent link field (by default |
| 854 |
``<parent_model_name>_ptr``) instead of an ``id`` field. |
| 855 |
|
| 856 |
Changing the queryset |
| 857 |
--------------------- |
| 858 |
|
| 859 |
By default, when you create a formset from a model, the formset will use a |
| 860 |
queryset that includes all objects in the model (e.g., |
| 861 |
``Author.objects.all()``). You can override this behavior by using the |
| 862 |
``queryset`` argument: |
| 863 |
|
| 864 |
.. code-block:: pycon |
| 865 |
|
| 866 |
>>> formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith="O")) |
| 867 |
|
| 868 |
Alternatively, you can create a subclass that sets ``self.queryset`` in |
| 869 |
``__init__``:: |
| 870 |
|
| 871 |
from django.forms import BaseModelFormSet |
| 872 |
from myapp.models import Author |
| 873 |
|
| 874 |
|
| 875 |
class BaseAuthorFormSet(BaseModelFormSet): |
| 876 |
def __init__(self, *args, **kwargs): |
| 877 |
super().__init__(*args, **kwargs) |
| 878 |
self.queryset = Author.objects.filter(name__startswith="O") |
| 879 |
|
| 880 |
Then, pass your ``BaseAuthorFormSet`` class to the factory function: |
| 881 |
|
| 882 |
.. code-block:: pycon |
| 883 |
|
| 884 |
>>> AuthorFormSet = modelformset_factory( |
| 885 |
... Author, fields=["name", "title"], formset=BaseAuthorFormSet |
| 886 |
... ) |
| 887 |
|
| 888 |
If you want to return a formset that doesn't include *any* preexisting |
| 889 |
instances of the model, you can specify an empty QuerySet: |
| 890 |
|
| 891 |
.. code-block:: pycon |
| 892 |
|
| 893 |
>>> AuthorFormSet(queryset=Author.objects.none()) |
| 894 |
|
| 895 |
Changing the form |
| 896 |
----------------- |
| 897 |
|
| 898 |
By default, when you use ``modelformset_factory``, a model form will |
| 899 |
be created using :func:`~django.forms.models.modelform_factory`. |
| 900 |
Often, it can be useful to specify a custom model form. For example, |
| 901 |
you can create a custom model form that has custom validation:: |
| 902 |
|
| 903 |
class AuthorForm(forms.ModelForm): |
| 904 |
class Meta: |
| 905 |
model = Author |
| 906 |
fields = ["name", "title"] |
| 907 |
|
| 908 |
def clean_name(self): |
| 909 |
# custom validation for the name field |
| 910 |
... |
| 911 |
|
| 912 |
Then, pass your model form to the factory function:: |
| 913 |
|
| 914 |
AuthorFormSet = modelformset_factory(Author, form=AuthorForm) |
| 915 |
|
| 916 |
It is not always necessary to define a custom model form. The |
| 917 |
``modelformset_factory`` function has several arguments which are |
| 918 |
passed through to ``modelform_factory``, which are described below. |
| 919 |
|
| 920 |
Specifying widgets to use in the form with ``widgets`` |
| 921 |
------------------------------------------------------ |
| 922 |
|
| 923 |
Using the ``widgets`` parameter, you can specify a dictionary of values to |
| 924 |
customize the ``ModelForm``’s widget class for a particular field. This |
| 925 |
works the same way as the ``widgets`` dictionary on the inner ``Meta`` |
| 926 |
class of a ``ModelForm`` works: |
| 927 |
|
| 928 |
.. code-block:: pycon |
| 929 |
|
| 930 |
>>> AuthorFormSet = modelformset_factory( |
| 931 |
... Author, |
| 932 |
... fields=["name", "title"], |
| 933 |
... widgets={"name": Textarea(attrs={"cols": 80, "rows": 20})}, |
| 934 |
... ) |
| 935 |
|
| 936 |
Enabling localization for fields with ``localized_fields`` |
| 937 |
---------------------------------------------------------- |
| 938 |
|
| 939 |
Using the ``localized_fields`` parameter, you can enable localization for |
| 940 |
fields in the form. |
| 941 |
|
| 942 |
>>> AuthorFormSet = modelformset_factory( |
| 943 |
... Author, fields=['name', 'title', 'birth_date'], |
| 944 |
... localized_fields=['birth_date']) |
| 945 |
|
| 946 |
If ``localized_fields`` is set to the special value ``'__all__'``, all fields |
| 947 |
will be localized. |
| 948 |
|
| 949 |
Providing initial values |
| 950 |
------------------------ |
| 951 |
|
| 952 |
As with regular formsets, it's possible to :ref:`specify initial data |
| 953 |
<formsets-initial-data>` for forms in the formset by specifying an ``initial`` |
| 954 |
parameter when instantiating the model formset class returned by |
| 955 |
:func:`~django.forms.models.modelformset_factory`. However, with model |
| 956 |
formsets, the initial values only apply to extra forms, those that aren't |
| 957 |
attached to an existing model instance. If the length of ``initial`` exceeds |
| 958 |
the number of extra forms, the excess initial data is ignored. If the extra |
| 959 |
forms with initial data aren't changed by the user, they won't be validated or |
| 960 |
saved. |
| 961 |
|
| 962 |
.. _saving-objects-in-the-formset: |
| 963 |
|
| 964 |
Saving objects in the formset |
| 965 |
----------------------------- |
| 966 |
|
| 967 |
As with a ``ModelForm``, you can save the data as a model object. This is done |
| 968 |
with the formset's ``save()`` method: |
| 969 |
|
| 970 |
.. code-block:: pycon |
| 971 |
|
| 972 |
# Create a formset instance with POST data. |
| 973 |
>>> formset = AuthorFormSet(request.POST) |
| 974 |
|
| 975 |
# Assuming all is valid, save the data. |
| 976 |
>>> instances = formset.save() |
| 977 |
|
| 978 |
The ``save()`` method returns the instances that have been saved to the |
| 979 |
database. If a given instance's data didn't change in the bound data, the |
| 980 |
instance won't be saved to the database and won't be included in the return |
| 981 |
value (``instances``, in the above example). |
| 982 |
|
| 983 |
When fields are missing from the form (for example because they have been |
| 984 |
excluded), these fields will not be set by the ``save()`` method. You can find |
| 985 |
more information about this restriction, which also holds for regular |
| 986 |
model forms, in `Selecting the fields to use`_. |
| 987 |
|
| 988 |
Pass ``commit=False`` to return the unsaved model instances: |
| 989 |
|
| 990 |
.. code-block:: pycon |
| 991 |
|
| 992 |
# don't save to the database |
| 993 |
>>> instances = formset.save(commit=False) |
| 994 |
>>> for instance in instances: |
| 995 |
... # do something with instance |
| 996 |
... instance.save() |
| 997 |
... |
| 998 |
|
| 999 |
This gives you the ability to attach data to the instances before saving them |
| 1000 |
to the database. If your formset contains a ``ManyToManyField``, you'll also |
| 1001 |
need to call ``formset.save_m2m()`` to ensure the many-to-many relationships |
| 1002 |
are saved properly. |
| 1003 |
|
| 1004 |
After calling ``save()``, your model formset will have three new attributes |
| 1005 |
containing the formset's changes: |
| 1006 |
|
| 1007 |
.. attribute:: models.BaseModelFormSet.changed_objects |
| 1008 |
.. attribute:: models.BaseModelFormSet.deleted_objects |
| 1009 |
.. attribute:: models.BaseModelFormSet.new_objects |
| 1010 |
|
| 1011 |
.. _model-formsets-max-num: |
| 1012 |
|
| 1013 |
Limiting the number of editable objects |
| 1014 |
--------------------------------------- |
| 1015 |
|
| 1016 |
As with regular formsets, you can use the ``max_num`` and ``extra`` parameters |
| 1017 |
to :func:`~django.forms.models.modelformset_factory` to limit the number of |
| 1018 |
extra forms displayed. |
| 1019 |
|
| 1020 |
``max_num`` does not prevent existing objects from being displayed: |
| 1021 |
|
| 1022 |
.. code-block:: pycon |
| 1023 |
|
| 1024 |
>>> Author.objects.order_by("name") |
| 1025 |
<QuerySet [<Author: Charles Baudelaire>, <Author: Paul Verlaine>, <Author: Walt Whitman>]> |
| 1026 |
|
| 1027 |
>>> AuthorFormSet = modelformset_factory(Author, fields=["name"], max_num=1) |
| 1028 |
>>> formset = AuthorFormSet(queryset=Author.objects.order_by("name")) |
| 1029 |
>>> [x.name for x in formset.get_queryset()] |
| 1030 |
['Charles Baudelaire', 'Paul Verlaine', 'Walt Whitman'] |
| 1031 |
|
| 1032 |
Also, ``extra=0`` doesn't prevent creation of new model instances as you can |
| 1033 |
:ref:`add additional forms with JavaScript <understanding-the-managementform>` |
| 1034 |
or send additional POST data. See :ref:`model-formsets-edit-only` on how to do |
| 1035 |
this. |
| 1036 |
|
| 1037 |
If the value of ``max_num`` is greater than the number of existing related |
| 1038 |
objects, up to ``extra`` additional blank forms will be added to the formset, |
| 1039 |
so long as the total number of forms does not exceed ``max_num``: |
| 1040 |
|
| 1041 |
.. code-block:: pycon |
| 1042 |
|
| 1043 |
>>> AuthorFormSet = modelformset_factory(Author, fields=["name"], max_num=4, extra=2) |
| 1044 |
>>> formset = AuthorFormSet(queryset=Author.objects.order_by("name")) |
| 1045 |
>>> for form in formset: |
| 1046 |
... print(form) |
| 1047 |
... |
| 1048 |
<div><label for="id_form-0-name">Name:</label><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"></div> |
| 1049 |
<div><label for="id_form-1-name">Name:</label><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"></div> |
| 1050 |
<div><label for="id_form-2-name">Name:</label><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"></div> |
| 1051 |
<div><label for="id_form-3-name">Name:</label><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"></div> |
| 1052 |
|
| 1053 |
A ``max_num`` value of ``None`` (the default) puts a high limit on the number |
| 1054 |
of forms displayed (1000). In practice this is equivalent to no limit. |
| 1055 |
|
| 1056 |
.. _model-formsets-edit-only: |
| 1057 |
|
| 1058 |
Preventing new objects creation |
| 1059 |
------------------------------- |
| 1060 |
|
| 1061 |
Using the ``edit_only`` parameter, you can prevent creation of any new |
| 1062 |
objects: |
| 1063 |
|
| 1064 |
.. code-block:: pycon |
| 1065 |
|
| 1066 |
>>> AuthorFormSet = modelformset_factory( |
| 1067 |
... Author, |
| 1068 |
... fields=["name", "title"], |
| 1069 |
... edit_only=True, |
| 1070 |
... ) |
| 1071 |
|
| 1072 |
Here, the formset will only edit existing ``Author`` instances. No other |
| 1073 |
objects will be created or edited. |
| 1074 |
|
| 1075 |
Using a model formset in a view |
| 1076 |
------------------------------- |
| 1077 |
|
| 1078 |
Model formsets are very similar to formsets. Let's say we want to present a |
| 1079 |
formset to edit ``Author`` model instances:: |
| 1080 |
|
| 1081 |
from django.forms import modelformset_factory |
| 1082 |
from django.shortcuts import render |
| 1083 |
from myapp.models import Author |
| 1084 |
|
| 1085 |
|
| 1086 |
def manage_authors(request): |
| 1087 |
AuthorFormSet = modelformset_factory(Author, fields=["name", "title"]) |
| 1088 |
if request.method == "POST": |
| 1089 |
formset = AuthorFormSet(request.POST, request.FILES) |
| 1090 |
if formset.is_valid(): |
| 1091 |
formset.save() |
| 1092 |
# do something. |
| 1093 |
else: |
| 1094 |
formset = AuthorFormSet() |
| 1095 |
return render(request, "manage_authors.html", {"formset": formset}) |
| 1096 |
|
| 1097 |
As you can see, the view logic of a model formset isn't drastically different |
| 1098 |
than that of a "normal" formset. The only difference is that we call |
| 1099 |
``formset.save()`` to save the data into the database. (This was described |
| 1100 |
above, in :ref:`saving-objects-in-the-formset`.) |
| 1101 |
|
| 1102 |
.. _model-formsets-overriding-clean: |
| 1103 |
|
| 1104 |
Overriding ``clean()`` on a ``ModelFormSet`` |
| 1105 |
-------------------------------------------- |
| 1106 |
|
| 1107 |
Just like with a ``ModelForm``, by default the ``clean()`` method of a |
| 1108 |
``ModelFormSet`` will validate that none of the items in the formset violate |
| 1109 |
the unique constraints on your model (either ``unique``, ``unique_together`` or |
| 1110 |
``unique_for_date|month|year``). If you want to override the ``clean()`` method |
| 1111 |
on a ``ModelFormSet`` and maintain this validation, you must call the parent |
| 1112 |
class's ``clean`` method:: |
| 1113 |
|
| 1114 |
from django.forms import BaseModelFormSet |
| 1115 |
|
| 1116 |
|
| 1117 |
class MyModelFormSet(BaseModelFormSet): |
| 1118 |
def clean(self): |
| 1119 |
super().clean() |
| 1120 |
# example custom validation across forms in the formset |
| 1121 |
for form in self.forms: |
| 1122 |
# your custom formset validation |
| 1123 |
... |
| 1124 |
|
| 1125 |
Also note that by the time you reach this step, individual model instances |
| 1126 |
have already been created for each ``Form``. Modifying a value in |
| 1127 |
``form.cleaned_data`` is not sufficient to affect the saved value. If you wish |
| 1128 |
to modify a value in ``ModelFormSet.clean()`` you must modify |
| 1129 |
``form.instance``:: |
| 1130 |
|
| 1131 |
from django.forms import BaseModelFormSet |
| 1132 |
|
| 1133 |
|
| 1134 |
class MyModelFormSet(BaseModelFormSet): |
| 1135 |
def clean(self): |
| 1136 |
super().clean() |
| 1137 |
|
| 1138 |
for form in self.forms: |
| 1139 |
name = form.cleaned_data["name"].upper() |
| 1140 |
form.cleaned_data["name"] = name |
| 1141 |
# update the instance value. |
| 1142 |
form.instance.name = name |
| 1143 |
|
| 1144 |
Using a custom queryset |
| 1145 |
----------------------- |
| 1146 |
|
| 1147 |
As stated earlier, you can override the default queryset used by the model |
| 1148 |
formset:: |
| 1149 |
|
| 1150 |
from django.forms import modelformset_factory |
| 1151 |
from django.shortcuts import render |
| 1152 |
from myapp.models import Author |
| 1153 |
|
| 1154 |
|
| 1155 |
def manage_authors(request): |
| 1156 |
AuthorFormSet = modelformset_factory(Author, fields=["name", "title"]) |
| 1157 |
queryset = Author.objects.filter(name__startswith="O") |
| 1158 |
if request.method == "POST": |
| 1159 |
formset = AuthorFormSet( |
| 1160 |
request.POST, |
| 1161 |
request.FILES, |
| 1162 |
queryset=queryset, |
| 1163 |
) |
| 1164 |
if formset.is_valid(): |
| 1165 |
formset.save() |
| 1166 |
# Do something. |
| 1167 |
else: |
| 1168 |
formset = AuthorFormSet(queryset=queryset) |
| 1169 |
return render(request, "manage_authors.html", {"formset": formset}) |
| 1170 |
|
| 1171 |
Note that we pass the ``queryset`` argument in both the ``POST`` and ``GET`` |
| 1172 |
cases in this example. |
| 1173 |
|
| 1174 |
Using the formset in the template |
| 1175 |
--------------------------------- |
| 1176 |
|
| 1177 |
There are three ways to render a formset in a Django template. |
| 1178 |
|
| 1179 |
First, you can let the formset do most of the work: |
| 1180 |
|
| 1181 |
.. code-block:: html+django |
| 1182 |
|
| 1183 |
<form method="post"> |
| 1184 |
{{ formset }} |
| 1185 |
</form> |
| 1186 |
|
| 1187 |
Second, you can manually render the formset, but let the form deal with |
| 1188 |
itself: |
| 1189 |
|
| 1190 |
.. code-block:: html+django |
| 1191 |
|
| 1192 |
<form method="post"> |
| 1193 |
{{ formset.management_form }} |
| 1194 |
{% for form in formset %} |
| 1195 |
{{ form }} |
| 1196 |
{% endfor %} |
| 1197 |
</form> |
| 1198 |
|
| 1199 |
When you manually render the forms yourself, be sure to render the management |
| 1200 |
form as shown above. See the :ref:`management form documentation |
| 1201 |
<understanding-the-managementform>`. |
| 1202 |
|
| 1203 |
Third, you can manually render each field: |
| 1204 |
|
| 1205 |
.. code-block:: html+django |
| 1206 |
|
| 1207 |
<form method="post"> |
| 1208 |
{{ formset.management_form }} |
| 1209 |
{% for form in formset %} |
| 1210 |
{% for field in form %} |
| 1211 |
{{ field.label_tag }} {{ field }} |
| 1212 |
{% endfor %} |
| 1213 |
{% endfor %} |
| 1214 |
</form> |
| 1215 |
|
| 1216 |
If you opt to use this third method and you don't iterate over the fields with |
| 1217 |
a ``{% for %}`` loop, you'll need to render the primary key field. For example, |
| 1218 |
if you were rendering the ``name`` and ``age`` fields of a model: |
| 1219 |
|
| 1220 |
.. code-block:: html+django |
| 1221 |
|
| 1222 |
<form method="post"> |
| 1223 |
{{ formset.management_form }} |
| 1224 |
{% for form in formset %} |
| 1225 |
{{ form.id }} |
| 1226 |
<ul> |
| 1227 |
<li>{{ form.name }}</li> |
| 1228 |
<li>{{ form.age }}</li> |
| 1229 |
</ul> |
| 1230 |
{% endfor %} |
| 1231 |
</form> |
| 1232 |
|
| 1233 |
Notice how we need to explicitly render ``{{ form.id }}``. This ensures that |
| 1234 |
the model formset, in the ``POST`` case, will work correctly. (This example |
| 1235 |
assumes a primary key named ``id``. If you've explicitly defined your own |
| 1236 |
primary key that isn't called ``id``, make sure it gets rendered.) |
| 1237 |
|
| 1238 |
.. _inline-formsets: |
| 1239 |
|
| 1240 |
Inline formsets |
| 1241 |
=============== |
| 1242 |
|
| 1243 |
.. class:: models.BaseInlineFormSet |
| 1244 |
|
| 1245 |
Inline formsets is a small abstraction layer on top of model formsets. These |
| 1246 |
simplify the case of working with related objects via a foreign key. Suppose |
| 1247 |
you have these two models:: |
| 1248 |
|
| 1249 |
from django.db import models |
| 1250 |
|
| 1251 |
|
| 1252 |
class Author(models.Model): |
| 1253 |
name = models.CharField(max_length=100) |
| 1254 |
|
| 1255 |
|
| 1256 |
class Book(models.Model): |
| 1257 |
author = models.ForeignKey(Author, on_delete=models.CASCADE) |
| 1258 |
title = models.CharField(max_length=100) |
| 1259 |
|
| 1260 |
If you want to create a formset that allows you to edit books belonging to |
| 1261 |
a particular author, you could do this: |
| 1262 |
|
| 1263 |
.. code-block:: pycon |
| 1264 |
|
| 1265 |
>>> from django.forms import inlineformset_factory |
| 1266 |
>>> BookFormSet = inlineformset_factory(Author, Book, fields=["title"]) |
| 1267 |
>>> author = Author.objects.get(name="Mike Royko") |
| 1268 |
>>> formset = BookFormSet(instance=author) |
| 1269 |
|
| 1270 |
``BookFormSet``'s :ref:`prefix <formset-prefix>` is ``'book_set'`` |
| 1271 |
(``<model name>_set`` ). If ``Book``'s ``ForeignKey`` to ``Author`` has a |
| 1272 |
:attr:`~django.db.models.ForeignKey.related_name`, that's used instead. |
| 1273 |
|
| 1274 |
.. note:: |
| 1275 |
|
| 1276 |
:func:`~django.forms.models.inlineformset_factory` uses |
| 1277 |
:func:`~django.forms.models.modelformset_factory` and marks |
| 1278 |
``can_delete=True``. |
| 1279 |
|
| 1280 |
.. seealso:: |
| 1281 |
|
| 1282 |
:ref:`Manually rendered can_delete and can_order <manually-rendered-can-delete-and-can-order>`. |
| 1283 |
|
| 1284 |
Overriding methods on an ``InlineFormSet`` |
| 1285 |
------------------------------------------ |
| 1286 |
|
| 1287 |
When overriding methods on ``InlineFormSet``, you should subclass |
| 1288 |
:class:`~models.BaseInlineFormSet` rather than |
| 1289 |
:class:`~models.BaseModelFormSet`. |
| 1290 |
|
| 1291 |
For example, if you want to override ``clean()``:: |
| 1292 |
|
| 1293 |
from django.forms import BaseInlineFormSet |
| 1294 |
|
| 1295 |
|
| 1296 |
class CustomInlineFormSet(BaseInlineFormSet): |
| 1297 |
def clean(self): |
| 1298 |
super().clean() |
| 1299 |
# example custom validation across forms in the formset |
| 1300 |
for form in self.forms: |
| 1301 |
# your custom formset validation |
| 1302 |
... |
| 1303 |
|
| 1304 |
See also :ref:`model-formsets-overriding-clean`. |
| 1305 |
|
| 1306 |
Then when you create your inline formset, pass in the optional argument |
| 1307 |
``formset``: |
| 1308 |
|
| 1309 |
.. code-block:: pycon |
| 1310 |
|
| 1311 |
>>> from django.forms import inlineformset_factory |
| 1312 |
>>> BookFormSet = inlineformset_factory( |
| 1313 |
... Author, Book, fields=["title"], formset=CustomInlineFormSet |
| 1314 |
... ) |
| 1315 |
>>> author = Author.objects.get(name="Mike Royko") |
| 1316 |
>>> formset = BookFormSet(instance=author) |
| 1317 |
|
| 1318 |
More than one foreign key to the same model |
| 1319 |
------------------------------------------- |
| 1320 |
|
| 1321 |
If your model contains more than one foreign key to the same model, you'll |
| 1322 |
need to resolve the ambiguity manually using ``fk_name``. For example, consider |
| 1323 |
the following model:: |
| 1324 |
|
| 1325 |
class Friendship(models.Model): |
| 1326 |
from_friend = models.ForeignKey( |
| 1327 |
Friend, |
| 1328 |
on_delete=models.CASCADE, |
| 1329 |
related_name="from_friends", |
| 1330 |
) |
| 1331 |
to_friend = models.ForeignKey( |
| 1332 |
Friend, |
| 1333 |
on_delete=models.CASCADE, |
| 1334 |
related_name="friends", |
| 1335 |
) |
| 1336 |
length_in_months = models.IntegerField() |
| 1337 |
|
| 1338 |
To resolve this, you can use ``fk_name`` to |
| 1339 |
:func:`~django.forms.models.inlineformset_factory`: |
| 1340 |
|
| 1341 |
.. code-block:: pycon |
| 1342 |
|
| 1343 |
>>> FriendshipFormSet = inlineformset_factory( |
| 1344 |
... Friend, Friendship, fk_name="from_friend", fields=["to_friend", "length_in_months"] |
| 1345 |
... ) |
| 1346 |
|
| 1347 |
Using an inline formset in a view |
| 1348 |
--------------------------------- |
| 1349 |
|
| 1350 |
You may want to provide a view that allows a user to edit the related objects |
| 1351 |
of a model. Here's how you can do that:: |
| 1352 |
|
| 1353 |
def manage_books(request, author_id): |
| 1354 |
author = Author.objects.get(pk=author_id) |
| 1355 |
BookInlineFormSet = inlineformset_factory(Author, Book, fields=["title"]) |
| 1356 |
if request.method == "POST": |
| 1357 |
formset = BookInlineFormSet(request.POST, request.FILES, instance=author) |
| 1358 |
if formset.is_valid(): |
| 1359 |
formset.save() |
| 1360 |
# Do something. Should generally end with a redirect. For example: |
| 1361 |
return HttpResponseRedirect(author.get_absolute_url()) |
| 1362 |
else: |
| 1363 |
formset = BookInlineFormSet(instance=author) |
| 1364 |
return render(request, "manage_books.html", {"formset": formset}) |
| 1365 |
|
| 1366 |
Notice how we pass ``instance`` in both the ``POST`` and ``GET`` cases. |
| 1367 |
|
| 1368 |
Specifying widgets to use in the inline form |
| 1369 |
-------------------------------------------- |
| 1370 |
|
| 1371 |
|
| 1372 |
``inlineformset_factory`` uses ``modelformset_factory`` and passes most |
| 1373 |
of its arguments to ``modelformset_factory``. This means you can use |
| 1374 |
the ``widgets`` parameter in much the same way as passing it to |
| 1375 |
``modelformset_factory``. See `Specifying widgets to use in the form with |
| 1376 |
widgets`_ above. |