modelforms.txt 40 KB

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