In Django working with choice fields in models, forms and templates is a common task. Choice fields allow you to provide predefined set of options for users to select from. In this blog post, will explore how to define and display choice values in Django forms and templates.
Defining Choice Fields in Models
Django models allow you to define choice fields using the models.CharField
or models.IntegerField
field types along with the choices
argument. For example, you can define a model with a status
field as follows:
from django.db import models
class MyModel(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
('archived', 'Archived'),
)
status = models.CharField(max_length=20, choices=STATUS_CHOICES)
Here we define a status
field with predefined choices for ‘Draft,’ ‘Published,’ and ‘Archived.’
Displaying Choices in Forms
When working with forms, Django provides ModelChoiceField
and TypedChoiceField
classes for choice fields. To use them in a form, you can define the field and specify the queryset
or choices
argument.
from django import forms
from .models import MyModel
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['status']
In this example we use a ModelChoiceField
to create a form field based on the status
field of MyModel
. The choices defined in the model will be displayed in the form.
Displaying Choices in Templates
To display choice values in templates, you can use the get_FOO_display
method, where FOO
is the name of the choice field. For example, to display the human-readable status in a template:
{{ my_model_instance.get_status_display }}
This code will display ‘Draft,’ ‘Published’ or ‘Archived’ depending on the value of the status
field.
Customizing Choice Display
You can customize the display of choice values by modifying the values in the choices
tuple in the model. For example you can change ‘Draft’ to ‘Draft Mode’ in the choices tuple to display ‘Draft Mode’ in forms and templates.
STATUS_CHOICES = (
('draft', 'Draft Mode'),
('published', 'Published'),
('archived', 'Archived'),
)
Working with choice values in Django is the straightforward, whether you defining choice fields in models, displaying them in forms or rendering them in templates. By understanding how to define and display choice values, you can build user-friendly web applications that make use of predefined options and selections.