class ModelChoiceField(**kwargs)
[source]
- Default widget:
Select
- Empty value:
None
- Normalizes to: A model instance.
- Validates that the given id exists in the queryset.
- Error message keys:
required
,invalid_choice
Allows the selection of a single model object, suitable for representing a foreign key. Note that the default widget for ModelChoiceField
becomes impractical when the number of entries increases. You should avoid using it for more than 100 items.
A single argument is required:
-
queryset
-
A
QuerySet
of model objects from which the choices for the field will be derived, and which will be used to validate the user’s selection.
ModelChoiceField
also takes two optional arguments:
-
empty_label
-
By default the
<select>
widget used byModelChoiceField
will have an empty choice at the top of the list. You can change the text of this label (which is"---------"
by default) with theempty_label
attribute, or you can disable the empty label entirely by settingempty_label
toNone
:# A custom empty label field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)") # No empty label field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
Note that if a
ModelChoiceField
is required and has a default initial value, no empty choice is created (regardless of the value ofempty_label
).
-
to_field_name
-
This optional argument is used to specify the field to use as the value of the choices in the field’s widget. Be sure it’s a unique field for the model, otherwise the selected value could match more than one object. By default it is set to
None
, in which case the primary key of each object will be used. For example:# No custom to_field_name field1 = forms.ModelChoiceField(queryset=...)
would yield:
<select id="id_field1" name="field1"> <option value="obj1.pk">Object1</option> <option value="obj2.pk">Object2</option> ... </select>
and:
# to_field_name provided field2 = forms.ModelChoiceField(queryset=..., to_field_name="name")
would yield:
<select id="id_field2" name="field2"> <option value="obj1.name">Object1</option> <option value="obj2.name">Object2</option> ... </select>
The __str__
(__unicode__
on Python 2) method of the model will be called to generate string representations of the objects for use in the field’s choices; to provide customized representations, subclass ModelChoiceField
and override label_from_instance
. This method will receive a model object, and should return a string suitable for representing it. For example:
from django.forms import ModelChoiceField class MyModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return "My Object #%i" % obj.id
Please login to continue.