Skip to main content

ModelChoiceField

A ChoiceField whose choices are a model QuerySet.

Attributes

AttributeTypeDescription
default_error_messagesdict = {"invalid_choice": "Select a valid choice. That choice is not one of the available choices."}A dictionary containing the default error message for invalid choices, used when a submitted value is not found within the available queryset.
iteratorclass = ModelChoiceIteratorThe class used to iterate over the queryset and generate the choice list for the field.
queryset[QuerySet](../../db/models/query/queryset.md?sid=django_db_models_query_queryset)The model QuerySet used to populate the choices for the field and to validate the selected value.
choicespropertyA property that returns a fresh ModelChoiceIterator to dynamically determine the available choices from the queryset.

Constructor

Signature

def ModelChoiceField(
queryset: [QuerySet](../../db/models/query/queryset.md?sid=django_db_models_query_queryset),
empty_label: string = "",
required: boolean = True,
widget: [Widget](../widgets/widget.md?sid=django_forms_widgets_widget) = null,
label: string = null,
initial: any = null,
help_text: string = "",
to_field_name: string = null,
limit_choices_to: dict|callable = null,
blank: boolean = False,
**kwargs: dict
) - > null

Parameters

NameTypeDescription
queryset[QuerySet](../../db/models/query/queryset.md?sid=django_db_models_query_queryset)The QuerySet of model instances to use for the field choices.
empty_labelstring = ""The label to use for the empty choice in the field.
requiredboolean = TrueWhether the field is required.
widget[Widget](../widgets/widget.md?sid=django_forms_widgets_widget) = nullThe widget to use for rendering the field.
labelstring = nullA display label for the field.
initialany = nullThe initial value for the field.
help_textstring = ""Additional help text to display with the field.
to_field_namestring = nullThe name of the model field to use as the value for choices.
limit_choices_to`dictcallable` = null
blankboolean = FalseWhether the field allows blank values.
**kwargsdictAdditional keyword arguments passed to the parent Field class.

Methods


validate_no_null_characters()

@classmethod
def validate_no_null_characters(
value: string
) - > null

Ensures the provided value does not contain null characters to prevent security vulnerabilities in database lookups.

Parameters

NameTypeDescription
valuestringThe input string to be checked for null characters.

Returns

TypeDescription
nullNothing if validation passes; raises a ValidationError if null characters are present.

get_limit_choices_to()

@classmethod
def get_limit_choices_to() - > dict|Q

Return limit_choices_to for this form field. If it is a callable, invoke it and return the result.

Returns

TypeDescription
`dictQ`

label_from_instance()

@classmethod
def label_from_instance(
obj: [Model](../../db/models/base/model.md?sid=django_db_models_base_model)
) - > string

Convert objects into strings and generate the labels for the choices presented by this object. Subclasses can override this method to customize the display of the choices.

Parameters

NameTypeDescription
obj[Model](../../db/models/base/model.md?sid=django_db_models_base_model)The model instance for which a choice label is being generated.

Returns

TypeDescription
stringThe string representation of the model instance to be used as a label in the UI.

prepare_value()

@classmethod
def prepare_value(
value: any
) - > any

Converts a model instance into its primary key or a specific field value for rendering in a widget.

Parameters

NameTypeDescription
valueanyThe value to prepare, which can be a model instance or a raw primary key.

Returns

TypeDescription
anyThe serializable value of the object, typically a primary key or the value of to_field_name.

to_python()

@classmethod
def to_python(
value: any
) - > [Model](../../db/models/base/model.md?sid=django_db_models_base_model)

Converts the input value (typically a primary key) into a concrete model instance by performing a database lookup.

Parameters

NameTypeDescription
valueanyThe raw input from the form, usually a primary key string or integer.

Returns

TypeDescription
[Model](../../db/models/base/model.md?sid=django_db_models_base_model)The model instance retrieved from the database, or None if the input is empty.

validate()

@classmethod
def validate(
value: any
) - > null

Performs basic field validation to ensure the value meets the required constraints.

Parameters

NameTypeDescription
valueanyThe value to validate against field requirements.

Returns

TypeDescription
nullNothing if validation passes; raises a ValidationError otherwise.

has_changed()

@classmethod
def has_changed(
initial: any,
data: any
) - > boolean

Determines if the current data value differs from the initial value by comparing their serialized string representations.

Parameters

NameTypeDescription
initialanyThe original value the field was populated with.
dataanyThe new data submitted via the form.

Returns

TypeDescription
booleanTrue if the value has changed from the initial state, False otherwise.