mirror of
https://github.com/django/django.git
synced 2025-08-02 18:13:02 +00:00
Fixed #24295 -- Allowed ModelForm meta to specify form field classes.
Thanks Carl Meyer and Markus Holtermann for the reviews.
This commit is contained in:
parent
e8cf4f8abe
commit
00a889167f
6 changed files with 92 additions and 26 deletions
|
@ -475,9 +475,8 @@ Overriding the default fields
|
|||
|
||||
The default field types, as described in the `Field types`_ table above, are
|
||||
sensible defaults. If you have a ``DateField`` in your model, chances are you'd
|
||||
want that to be represented as a ``DateField`` in your form. But
|
||||
``ModelForm`` gives you the flexibility of changing the form field type and
|
||||
widget for a given model field.
|
||||
want that to be represented as a ``DateField`` in your form. But ``ModelForm``
|
||||
gives you the flexibility of changing the form field for a given model.
|
||||
|
||||
To specify a custom widget for a field, use the ``widgets`` attribute of the
|
||||
inner ``Meta`` class. This should be a dictionary mapping field names to widget
|
||||
|
@ -525,9 +524,8 @@ the ``name`` field::
|
|||
},
|
||||
}
|
||||
|
||||
Finally, if you want complete control over of a field -- including its type,
|
||||
validators, etc. -- you can do this by declaratively specifying fields like you
|
||||
would in a regular ``Form``.
|
||||
You can also specify ``field_classes`` to customize the type of fields
|
||||
instantiated by the form.
|
||||
|
||||
For example, if you wanted to use ``MySlugFormField`` for the ``slug``
|
||||
field, you could do the following::
|
||||
|
@ -536,13 +534,18 @@ field, you could do the following::
|
|||
from myapp.models import Article
|
||||
|
||||
class ArticleForm(ModelForm):
|
||||
slug = MySlugFormField()
|
||||
|
||||
class Meta:
|
||||
model = Article
|
||||
fields = ['pub_date', 'headline', 'content', 'reporter', 'slug']
|
||||
field_classes = {
|
||||
'slug': MySlugFormField,
|
||||
}
|
||||
|
||||
|
||||
Finally, if you want complete control over of a field -- including its type,
|
||||
validators, required, etc. -- you can do this by declaratively specifying
|
||||
fields like you would in a regular ``Form``.
|
||||
|
||||
If you want to specify a field's validators, you can do so by defining
|
||||
the field declaratively and setting its ``validators`` parameter::
|
||||
|
||||
|
@ -556,6 +559,10 @@ the field declaratively and setting its ``validators`` parameter::
|
|||
model = Article
|
||||
fields = ['pub_date', 'headline', 'content', 'reporter', 'slug']
|
||||
|
||||
.. versionadded:: 1.9
|
||||
|
||||
The ``Meta.field_classes`` attribute was added.
|
||||
|
||||
.. note::
|
||||
|
||||
When you explicitly instantiate a form field like this, it is important to
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue