modelforms.txt 45 KB

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