modelforms.txt 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  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 ``save()`` on a form, all data -- including many-to-many data --
  283. is saved without the need for any additional method calls. 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``). Note that the ``widgets``
  380. dictionary is ignored for a model field with a non-empty ``choices`` attribute.
  381. In this case, you must override the form field to use a different widget.
  382. Similarly, you can specify the ``labels``, ``help_texts`` and ``error_messages``
  383. attributes of the inner ``Meta`` class if you want to further customize a field.
  384. For example if you wanted to customize the wording of all user facing strings for
  385. the ``name`` field::
  386. from django.utils.translation import gettext_lazy as _
  387. class AuthorForm(ModelForm):
  388. class Meta:
  389. model = Author
  390. fields = ('name', 'title', 'birth_date')
  391. labels = {
  392. 'name': _('Writer'),
  393. }
  394. help_texts = {
  395. 'name': _('Some useful help text.'),
  396. }
  397. error_messages = {
  398. 'name': {
  399. 'max_length': _("This writer's name is too long."),
  400. },
  401. }
  402. You can also specify ``field_classes`` to customize the type of fields
  403. instantiated by the form.
  404. For example, if you wanted to use ``MySlugFormField`` for the ``slug``
  405. field, you could do the following::
  406. from django.forms import ModelForm
  407. from myapp.models import Article
  408. class ArticleForm(ModelForm):
  409. class Meta:
  410. model = Article
  411. fields = ['pub_date', 'headline', 'content', 'reporter', 'slug']
  412. field_classes = {
  413. 'slug': MySlugFormField,
  414. }
  415. Finally, if you want complete control over of a field -- including its type,
  416. validators, required, etc. -- you can do this by declaratively specifying
  417. fields like you would in a regular ``Form``.
  418. If you want to specify a field's validators, you can do so by defining
  419. the field declaratively and setting its ``validators`` parameter::
  420. from django.forms import CharField, ModelForm
  421. from myapp.models import Article
  422. class ArticleForm(ModelForm):
  423. slug = CharField(validators=[validate_slug])
  424. class Meta:
  425. model = Article
  426. fields = ['pub_date', 'headline', 'content', 'reporter', 'slug']
  427. .. note::
  428. When you explicitly instantiate a form field like this, it is important to
  429. understand how ``ModelForm`` and regular ``Form`` are related.
  430. ``ModelForm`` is a regular ``Form`` which can automatically generate
  431. certain fields. The fields that are automatically generated depend on
  432. the content of the ``Meta`` class and on which fields have already been
  433. defined declaratively. Basically, ``ModelForm`` will **only** generate fields
  434. that are **missing** from the form, or in other words, fields that weren't
  435. defined declaratively.
  436. Fields defined declaratively are left as-is, therefore any customizations
  437. made to ``Meta`` attributes such as ``widgets``, ``labels``, ``help_texts``,
  438. or ``error_messages`` are ignored; these only apply to fields that are
  439. generated automatically.
  440. Similarly, fields defined declaratively do not draw their attributes like
  441. ``max_length`` or ``required`` from the corresponding model. If you want to
  442. maintain the behavior specified in the model, you must set the relevant
  443. arguments explicitly when declaring the form field.
  444. For example, if the ``Article`` model looks like this::
  445. class Article(models.Model):
  446. headline = models.CharField(
  447. max_length=200,
  448. null=True,
  449. blank=True,
  450. help_text='Use puns liberally',
  451. )
  452. content = models.TextField()
  453. and you want to do some custom validation for ``headline``, while keeping
  454. the ``blank`` and ``help_text`` values as specified, you might define
  455. ``ArticleForm`` like this::
  456. class ArticleForm(ModelForm):
  457. headline = MyFormField(
  458. max_length=200,
  459. required=False,
  460. help_text='Use puns liberally',
  461. )
  462. class Meta:
  463. model = Article
  464. fields = ['headline', 'content']
  465. You must ensure that the type of the form field can be used to set the
  466. contents of the corresponding model field. When they are not compatible,
  467. you will get a ``ValueError`` as no implicit conversion takes place.
  468. See the :doc:`form field documentation </ref/forms/fields>` for more information
  469. on fields and their arguments.
  470. Enabling localization of fields
  471. -------------------------------
  472. By default, the fields in a ``ModelForm`` will not localize their data. To
  473. enable localization for fields, you can use the ``localized_fields``
  474. attribute on the ``Meta`` class.
  475. >>> from django.forms import ModelForm
  476. >>> from myapp.models import Author
  477. >>> class AuthorForm(ModelForm):
  478. ... class Meta:
  479. ... model = Author
  480. ... localized_fields = ('birth_date',)
  481. If ``localized_fields`` is set to the special value ``'__all__'``, all fields
  482. will be localized.
  483. Form inheritance
  484. ----------------
  485. As with basic forms, you can extend and reuse ``ModelForms`` by inheriting
  486. them. This is useful if you need to declare extra fields or extra methods on a
  487. parent class for use in a number of forms derived from models. For example,
  488. using the previous ``ArticleForm`` class::
  489. >>> class EnhancedArticleForm(ArticleForm):
  490. ... def clean_pub_date(self):
  491. ... ...
  492. This creates a form that behaves identically to ``ArticleForm``, except there's
  493. some extra validation and cleaning for the ``pub_date`` field.
  494. You can also subclass the parent's ``Meta`` inner class if you want to change
  495. the ``Meta.fields`` or ``Meta.exclude`` lists::
  496. >>> class RestrictedArticleForm(EnhancedArticleForm):
  497. ... class Meta(ArticleForm.Meta):
  498. ... exclude = ('body',)
  499. This adds the extra method from the ``EnhancedArticleForm`` and modifies
  500. the original ``ArticleForm.Meta`` to remove one field.
  501. There are a couple of things to note, however.
  502. * Normal Python name resolution rules apply. If you have multiple base
  503. classes that declare a ``Meta`` inner class, only the first one will be
  504. used. This means the child's ``Meta``, if it exists, otherwise the
  505. ``Meta`` of the first parent, etc.
  506. * It's possible to inherit from both ``Form`` and ``ModelForm`` simultaneously,
  507. however, you must ensure that ``ModelForm`` appears first in the MRO. This is
  508. because these classes rely on different metaclasses and a class can only have
  509. one metaclass.
  510. * It's possible to declaratively remove a ``Field`` inherited from a parent class by
  511. setting the name to be ``None`` on the subclass.
  512. You can only use this technique to opt out from a field defined declaratively
  513. by a parent class; it won't prevent the ``ModelForm`` metaclass from generating
  514. a default field. To opt-out from default fields, see
  515. :ref:`modelforms-selecting-fields`.
  516. Providing initial values
  517. ------------------------
  518. As with regular forms, it's possible to specify initial data for forms by
  519. specifying an ``initial`` parameter when instantiating the form. Initial
  520. values provided this way will override both initial values from the form field
  521. and values from an attached model instance. For example::
  522. >>> article = Article.objects.get(pk=1)
  523. >>> article.headline
  524. 'My headline'
  525. >>> form = ArticleForm(initial={'headline': 'Initial headline'}, instance=article)
  526. >>> form['headline'].value()
  527. 'Initial headline'
  528. .. _modelforms-factory:
  529. ModelForm factory function
  530. --------------------------
  531. You can create forms from a given model using the standalone function
  532. :func:`~django.forms.models.modelform_factory`, instead of using a class
  533. definition. This may be more convenient if you do not have many customizations
  534. to make::
  535. >>> from django.forms import modelform_factory
  536. >>> from myapp.models import Book
  537. >>> BookForm = modelform_factory(Book, fields=("author", "title"))
  538. This can also be used to make modifications to existing forms, for example by
  539. specifying the widgets to be used for a given field::
  540. >>> from django.forms import Textarea
  541. >>> Form = modelform_factory(Book, form=BookForm,
  542. ... widgets={"title": Textarea()})
  543. The fields to include can be specified using the ``fields`` and ``exclude``
  544. keyword arguments, or the corresponding attributes on the ``ModelForm`` inner
  545. ``Meta`` class. Please see the ``ModelForm`` :ref:`modelforms-selecting-fields`
  546. documentation.
  547. ... or enable localization for specific fields::
  548. >>> Form = modelform_factory(Author, form=AuthorForm, localized_fields=("birth_date",))
  549. .. _model-formsets:
  550. Model formsets
  551. ==============
  552. .. class:: models.BaseModelFormSet
  553. Like :doc:`regular formsets </topics/forms/formsets>`, Django provides a couple
  554. of enhanced formset classes to make working with Django models more
  555. convenient. Let's reuse the ``Author`` model from above::
  556. >>> from django.forms import modelformset_factory
  557. >>> from myapp.models import Author
  558. >>> AuthorFormSet = modelformset_factory(Author, fields=('name', 'title'))
  559. Using ``fields`` restricts the formset to use only the given fields.
  560. Alternatively, you can take an "opt-out" approach, specifying which fields to
  561. exclude::
  562. >>> AuthorFormSet = modelformset_factory(Author, exclude=('birth_date',))
  563. This will create a formset that is capable of working with the data associated
  564. with the ``Author`` model. It works just like a regular formset::
  565. >>> formset = AuthorFormSet()
  566. >>> print(formset)
  567. <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">
  568. <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>
  569. <tr><th><label for="id_form-0-title">Title:</label></th><td><select name="form-0-title" id="id_form-0-title">
  570. <option value="" selected>---------</option>
  571. <option value="MR">Mr.</option>
  572. <option value="MRS">Mrs.</option>
  573. <option value="MS">Ms.</option>
  574. </select><input type="hidden" name="form-0-id" id="id_form-0-id"></td></tr>
  575. .. note::
  576. :func:`~django.forms.models.modelformset_factory` uses
  577. :func:`~django.forms.formsets.formset_factory` to generate formsets. This
  578. means that a model formset is an extension of a basic formset that knows
  579. how to interact with a particular model.
  580. .. note::
  581. When using :ref:`multi-table inheritance <multi-table-inheritance>`, forms
  582. generated by a formset factory will contain a parent link field (by default
  583. ``<parent_model_name>_ptr``) instead of an ``id`` field.
  584. Changing the queryset
  585. ---------------------
  586. By default, when you create a formset from a model, the formset will use a
  587. queryset that includes all objects in the model (e.g.,
  588. ``Author.objects.all()``). You can override this behavior by using the
  589. ``queryset`` argument::
  590. >>> formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O'))
  591. Alternatively, you can create a subclass that sets ``self.queryset`` in
  592. ``__init__``::
  593. from django.forms import BaseModelFormSet
  594. from myapp.models import Author
  595. class BaseAuthorFormSet(BaseModelFormSet):
  596. def __init__(self, *args, **kwargs):
  597. super().__init__(*args, **kwargs)
  598. self.queryset = Author.objects.filter(name__startswith='O')
  599. Then, pass your ``BaseAuthorFormSet`` class to the factory function::
  600. >>> AuthorFormSet = modelformset_factory(
  601. ... Author, fields=('name', 'title'), formset=BaseAuthorFormSet)
  602. If you want to return a formset that doesn't include *any* pre-existing
  603. instances of the model, you can specify an empty QuerySet::
  604. >>> AuthorFormSet(queryset=Author.objects.none())
  605. Changing the form
  606. -----------------
  607. By default, when you use ``modelformset_factory``, a model form will
  608. be created using :func:`~django.forms.models.modelform_factory`.
  609. Often, it can be useful to specify a custom model form. For example,
  610. you can create a custom model form that has custom validation::
  611. class AuthorForm(forms.ModelForm):
  612. class Meta:
  613. model = Author
  614. fields = ('name', 'title')
  615. def clean_name(self):
  616. # custom validation for the name field
  617. ...
  618. Then, pass your model form to the factory function::
  619. AuthorFormSet = modelformset_factory(Author, form=AuthorForm)
  620. It is not always necessary to define a custom model form. The
  621. ``modelformset_factory`` function has several arguments which are
  622. passed through to ``modelform_factory``, which are described below.
  623. Specifying widgets to use in the form with ``widgets``
  624. ------------------------------------------------------
  625. Using the ``widgets`` parameter, you can specify a dictionary of values to
  626. customize the ``ModelForm``’s widget class for a particular field. This
  627. works the same way as the ``widgets`` dictionary on the inner ``Meta``
  628. class of a ``ModelForm`` works::
  629. >>> AuthorFormSet = modelformset_factory(
  630. ... Author, fields=('name', 'title'),
  631. ... widgets={'name': Textarea(attrs={'cols': 80, 'rows': 20})})
  632. Enabling localization for fields with ``localized_fields``
  633. ----------------------------------------------------------
  634. Using the ``localized_fields`` parameter, you can enable localization for
  635. fields in the form.
  636. >>> AuthorFormSet = modelformset_factory(
  637. ... Author, fields=('name', 'title', 'birth_date'),
  638. ... localized_fields=('birth_date',))
  639. If ``localized_fields`` is set to the special value ``'__all__'``, all fields
  640. will be localized.
  641. Providing initial values
  642. ------------------------
  643. As with regular formsets, it's possible to :ref:`specify initial data
  644. <formsets-initial-data>` for forms in the formset by specifying an ``initial``
  645. parameter when instantiating the model formset class returned by
  646. :func:`~django.forms.models.modelformset_factory`. However, with model
  647. formsets, the initial values only apply to extra forms, those that aren't
  648. attached to an existing model instance. If the length of ``initial`` exceeds
  649. the number of extra forms, the excess initial data is ignored. If the extra
  650. forms with initial data aren't changed by the user, they won't be validated or
  651. saved.
  652. .. _saving-objects-in-the-formset:
  653. Saving objects in the formset
  654. -----------------------------
  655. As with a ``ModelForm``, you can save the data as a model object. This is done
  656. with the formset's ``save()`` method:
  657. .. code-block:: python
  658. # Create a formset instance with POST data.
  659. >>> formset = AuthorFormSet(request.POST)
  660. # Assuming all is valid, save the data.
  661. >>> instances = formset.save()
  662. The ``save()`` method returns the instances that have been saved to the
  663. database. If a given instance's data didn't change in the bound data, the
  664. instance won't be saved to the database and won't be included in the return
  665. value (``instances``, in the above example).
  666. When fields are missing from the form (for example because they have been
  667. excluded), these fields will not be set by the ``save()`` method. You can find
  668. more information about this restriction, which also holds for regular
  669. ``ModelForms``, in `Selecting the fields to use`_.
  670. Pass ``commit=False`` to return the unsaved model instances:
  671. .. code-block:: python
  672. # don't save to the database
  673. >>> instances = formset.save(commit=False)
  674. >>> for instance in instances:
  675. ... # do something with instance
  676. ... instance.save()
  677. This gives you the ability to attach data to the instances before saving them
  678. to the database. If your formset contains a ``ManyToManyField``, you'll also
  679. need to call ``formset.save_m2m()`` to ensure the many-to-many relationships
  680. are saved properly.
  681. After calling ``save()``, your model formset will have three new attributes
  682. containing the formset's changes:
  683. .. attribute:: models.BaseModelFormSet.changed_objects
  684. .. attribute:: models.BaseModelFormSet.deleted_objects
  685. .. attribute:: models.BaseModelFormSet.new_objects
  686. .. _model-formsets-max-num:
  687. Limiting the number of editable objects
  688. ---------------------------------------
  689. As with regular formsets, you can use the ``max_num`` and ``extra`` parameters
  690. to :func:`~django.forms.models.modelformset_factory` to limit the number of
  691. extra forms displayed.
  692. ``max_num`` does not prevent existing objects from being displayed::
  693. >>> Author.objects.order_by('name')
  694. <QuerySet [<Author: Charles Baudelaire>, <Author: Paul Verlaine>, <Author: Walt Whitman>]>
  695. >>> AuthorFormSet = modelformset_factory(Author, fields=('name',), max_num=1)
  696. >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
  697. >>> [x.name for x in formset.get_queryset()]
  698. ['Charles Baudelaire', 'Paul Verlaine', 'Walt Whitman']
  699. Also, ``extra=0`` doesn't prevent creation of new model instances as you can
  700. :ref:`add additional forms with JavaScript <understanding-the-managementform>`
  701. or send additional POST data. Formsets `don't yet provide functionality
  702. <https://code.djangoproject.com/ticket/26142>`_ for an "edit only" view that
  703. prevents creation of new instances.
  704. If the value of ``max_num`` is greater than the number of existing related
  705. objects, up to ``extra`` additional blank forms will be added to the formset,
  706. so long as the total number of forms does not exceed ``max_num``::
  707. >>> AuthorFormSet = modelformset_factory(Author, fields=('name',), max_num=4, extra=2)
  708. >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
  709. >>> for form in formset:
  710. ... print(form.as_table())
  711. <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>
  712. <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>
  713. <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>
  714. <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>
  715. A ``max_num`` value of ``None`` (the default) puts a high limit on the number
  716. of forms displayed (1000). In practice this is equivalent to no limit.
  717. Using a model formset in a view
  718. -------------------------------
  719. Model formsets are very similar to formsets. Let's say we want to present a
  720. formset to edit ``Author`` model instances::
  721. from django.forms import modelformset_factory
  722. from django.shortcuts import render
  723. from myapp.models import Author
  724. def manage_authors(request):
  725. AuthorFormSet = modelformset_factory(Author, fields=('name', 'title'))
  726. if request.method == 'POST':
  727. formset = AuthorFormSet(request.POST, request.FILES)
  728. if formset.is_valid():
  729. formset.save()
  730. # do something.
  731. else:
  732. formset = AuthorFormSet()
  733. return render(request, 'manage_authors.html', {'formset': formset})
  734. As you can see, the view logic of a model formset isn't drastically different
  735. than that of a "normal" formset. The only difference is that we call
  736. ``formset.save()`` to save the data into the database. (This was described
  737. above, in :ref:`saving-objects-in-the-formset`.)
  738. .. _model-formsets-overriding-clean:
  739. Overriding ``clean()`` on a ``ModelFormSet``
  740. --------------------------------------------
  741. Just like with ``ModelForms``, by default the ``clean()`` method of a
  742. ``ModelFormSet`` will validate that none of the items in the formset violate
  743. the unique constraints on your model (either ``unique``, ``unique_together`` or
  744. ``unique_for_date|month|year``). If you want to override the ``clean()`` method
  745. on a ``ModelFormSet`` and maintain this validation, you must call the parent
  746. class's ``clean`` method::
  747. from django.forms import BaseModelFormSet
  748. class MyModelFormSet(BaseModelFormSet):
  749. def clean(self):
  750. super().clean()
  751. # example custom validation across forms in the formset
  752. for form in self.forms:
  753. # your custom formset validation
  754. ...
  755. Also note that by the time you reach this step, individual model instances
  756. have already been created for each ``Form``. Modifying a value in
  757. ``form.cleaned_data`` is not sufficient to affect the saved value. If you wish
  758. to modify a value in ``ModelFormSet.clean()`` you must modify
  759. ``form.instance``::
  760. from django.forms import BaseModelFormSet
  761. class MyModelFormSet(BaseModelFormSet):
  762. def clean(self):
  763. super().clean()
  764. for form in self.forms:
  765. name = form.cleaned_data['name'].upper()
  766. form.cleaned_data['name'] = name
  767. # update the instance value.
  768. form.instance.name = name
  769. Using a custom queryset
  770. -----------------------
  771. As stated earlier, you can override the default queryset used by the model
  772. formset::
  773. from django.forms import modelformset_factory
  774. from django.shortcuts import render
  775. from myapp.models import Author
  776. def manage_authors(request):
  777. AuthorFormSet = modelformset_factory(Author, fields=('name', 'title'))
  778. if request.method == "POST":
  779. formset = AuthorFormSet(
  780. request.POST, request.FILES,
  781. queryset=Author.objects.filter(name__startswith='O'),
  782. )
  783. if formset.is_valid():
  784. formset.save()
  785. # Do something.
  786. else:
  787. formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O'))
  788. return render(request, 'manage_authors.html', {'formset': formset})
  789. Note that we pass the ``queryset`` argument in both the ``POST`` and ``GET``
  790. cases in this example.
  791. Using the formset in the template
  792. ---------------------------------
  793. .. highlight:: html+django
  794. There are three ways to render a formset in a Django template.
  795. First, you can let the formset do most of the work::
  796. <form method="post">
  797. {{ formset }}
  798. </form>
  799. Second, you can manually render the formset, but let the form deal with
  800. itself::
  801. <form method="post">
  802. {{ formset.management_form }}
  803. {% for form in formset %}
  804. {{ form }}
  805. {% endfor %}
  806. </form>
  807. When you manually render the forms yourself, be sure to render the management
  808. form as shown above. See the :ref:`management form documentation
  809. <understanding-the-managementform>`.
  810. Third, you can manually render each field::
  811. <form method="post">
  812. {{ formset.management_form }}
  813. {% for form in formset %}
  814. {% for field in form %}
  815. {{ field.label_tag }} {{ field }}
  816. {% endfor %}
  817. {% endfor %}
  818. </form>
  819. If you opt to use this third method and you don't iterate over the fields with
  820. a ``{% for %}`` loop, you'll need to render the primary key field. For example,
  821. if you were rendering the ``name`` and ``age`` fields of a model::
  822. <form method="post">
  823. {{ formset.management_form }}
  824. {% for form in formset %}
  825. {{ form.id }}
  826. <ul>
  827. <li>{{ form.name }}</li>
  828. <li>{{ form.age }}</li>
  829. </ul>
  830. {% endfor %}
  831. </form>
  832. Notice how we need to explicitly render ``{{ form.id }}``. This ensures that
  833. the model formset, in the ``POST`` case, will work correctly. (This example
  834. assumes a primary key named ``id``. If you've explicitly defined your own
  835. primary key that isn't called ``id``, make sure it gets rendered.)
  836. .. highlight:: python
  837. .. _inline-formsets:
  838. Inline formsets
  839. ===============
  840. .. class:: models.BaseInlineFormSet
  841. Inline formsets is a small abstraction layer on top of model formsets. These
  842. simplify the case of working with related objects via a foreign key. Suppose
  843. you have these two models::
  844. from django.db import models
  845. class Author(models.Model):
  846. name = models.CharField(max_length=100)
  847. class Book(models.Model):
  848. author = models.ForeignKey(Author, on_delete=models.CASCADE)
  849. title = models.CharField(max_length=100)
  850. If you want to create a formset that allows you to edit books belonging to
  851. a particular author, you could do this::
  852. >>> from django.forms import inlineformset_factory
  853. >>> BookFormSet = inlineformset_factory(Author, Book, fields=('title',))
  854. >>> author = Author.objects.get(name='Mike Royko')
  855. >>> formset = BookFormSet(instance=author)
  856. ``BookFormSet``'s :ref:`prefix <formset-prefix>` is ``'book_set'``
  857. (``<model name>_set`` ). If ``Book``'s ``ForeignKey`` to ``Author`` has a
  858. :attr:`~django.db.models.ForeignKey.related_name`, that's used instead.
  859. .. note::
  860. :func:`~django.forms.models.inlineformset_factory` uses
  861. :func:`~django.forms.models.modelformset_factory` and marks
  862. ``can_delete=True``.
  863. .. seealso::
  864. :ref:`Manually rendered can_delete and can_order <manually-rendered-can-delete-and-can-order>`.
  865. Overriding methods on an ``InlineFormSet``
  866. ------------------------------------------
  867. When overriding methods on ``InlineFormSet``, you should subclass
  868. :class:`~models.BaseInlineFormSet` rather than
  869. :class:`~models.BaseModelFormSet`.
  870. For example, if you want to override ``clean()``::
  871. from django.forms import BaseInlineFormSet
  872. class CustomInlineFormSet(BaseInlineFormSet):
  873. def clean(self):
  874. super().clean()
  875. # example custom validation across forms in the formset
  876. for form in self.forms:
  877. # your custom formset validation
  878. ...
  879. See also :ref:`model-formsets-overriding-clean`.
  880. Then when you create your inline formset, pass in the optional argument
  881. ``formset``::
  882. >>> from django.forms import inlineformset_factory
  883. >>> BookFormSet = inlineformset_factory(Author, Book, fields=('title',),
  884. ... formset=CustomInlineFormSet)
  885. >>> author = Author.objects.get(name='Mike Royko')
  886. >>> formset = BookFormSet(instance=author)
  887. More than one foreign key to the same model
  888. -------------------------------------------
  889. If your model contains more than one foreign key to the same model, you'll
  890. need to resolve the ambiguity manually using ``fk_name``. For example, consider
  891. the following model::
  892. class Friendship(models.Model):
  893. from_friend = models.ForeignKey(
  894. Friend,
  895. on_delete=models.CASCADE,
  896. related_name='from_friends',
  897. )
  898. to_friend = models.ForeignKey(
  899. Friend,
  900. on_delete=models.CASCADE,
  901. related_name='friends',
  902. )
  903. length_in_months = models.IntegerField()
  904. To resolve this, you can use ``fk_name`` to
  905. :func:`~django.forms.models.inlineformset_factory`::
  906. >>> FriendshipFormSet = inlineformset_factory(Friend, Friendship, fk_name='from_friend',
  907. ... fields=('to_friend', 'length_in_months'))
  908. Using an inline formset in a view
  909. ---------------------------------
  910. You may want to provide a view that allows a user to edit the related objects
  911. of a model. Here's how you can do that::
  912. def manage_books(request, author_id):
  913. author = Author.objects.get(pk=author_id)
  914. BookInlineFormSet = inlineformset_factory(Author, Book, fields=('title',))
  915. if request.method == "POST":
  916. formset = BookInlineFormSet(request.POST, request.FILES, instance=author)
  917. if formset.is_valid():
  918. formset.save()
  919. # Do something. Should generally end with a redirect. For example:
  920. return HttpResponseRedirect(author.get_absolute_url())
  921. else:
  922. formset = BookInlineFormSet(instance=author)
  923. return render(request, 'manage_books.html', {'formset': formset})
  924. Notice how we pass ``instance`` in both the ``POST`` and ``GET`` cases.
  925. Specifying widgets to use in the inline form
  926. --------------------------------------------
  927. ``inlineformset_factory`` uses ``modelformset_factory`` and passes most
  928. of its arguments to ``modelformset_factory``. This means you can use
  929. the ``widgets`` parameter in much the same way as passing it to
  930. ``modelformset_factory``. See `Specifying widgets to use in the form with
  931. widgets`_ above.