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