modelforms.txt 48 KB

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