modelforms.txt 48 KB

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