modelforms.txt 48 KB

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