modelforms.txt 41 KB

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