modelforms.txt 47 KB

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