2
0

modelforms.txt 50 KB

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