Skip to content

Instantly share code, notes, and snippets.

@amelieykw
Last active July 18, 2018 15:07
Show Gist options
  • Save amelieykw/a13aba60706cb8ced40ebdf586144728 to your computer and use it in GitHub Desktop.
Save amelieykw/a13aba60706cb8ced40ebdf586144728 to your computer and use it in GitHub Desktop.
[Django - Forms Field - ModelChoiceField] #ModelChoiceField #Django #Forms #Field
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 are derived and which is used to validate the user’s selection. It’s evaluated when the form is rendered.

ModelChoiceField also takes two optional arguments:

two optional arguments: 1. empty_label

By default the <select> widget used by ModelChoiceField will have an empty choice at the top of the list. You can change the text of this label (which is "---------" by default) with the empty_label attribute, or you can disable the empty label entirely by setting empty_label to None:

# 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 of empty_label).

two optional arguments: 2. 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() 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment