modelforms.txt 45 KB

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