Table of contents
1.
Introduction
2.
Field.choices
3.
Named groups for organizing data
4.
Using Enumeration
5.
Frequently Asked Questions
6.
Key Takeaways
Last Updated: Mar 27, 2024

How to use Django Field Choices?

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Forms are present on all websites. They serve the purpose of collecting data from the users. When creating a Form class in Django, one of the essential parts is defining the form’s fields. For some forms, we might use drop-downs, then we will have to provide choices for those fields. In this blog, we will see how that's done. 

 

In this blog, we are discussing Django field choices. To read more about Django, check out this blog.

Field.choices

Django field choices are sequences consisting of iterables of exactly two items (e.g. [(A, B), (C, D) ...]) to use as choices for some field. If the choices are provided, they're enforced by model validation. The default form widget will be a select box with specified choices, not the standard text field.

 

The first element in each tuple is the actual value set on the model, and the second element is the human-readable name.

 

Let us see a code snippet for the Django field choices.

DAYS_OF_THE_WEEK = [
   ('SUN', 'Sunday),
   ('MON', 'Monday'),
   ('TUE', 'Tuesday’),
   (‘WED', ‘Wednesday’),
  ('THURS', 'Thursday’),
  ('FRI', 'Friday’),
  ('SAT', 'Saturday’),
]
You can also try this code with Online Python Compiler
Run Code

 

In the above code, the first element present in each tuple is the actual value set on the model, whereas the second element is the human-readable name.

 

Let us create Django field choices with the above days of the week in our Django project named FieldChoices. Assume there is a field to select the day of the week. The choices will be Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday.

from django.db import models

# Specifying the choices
DAYS_OF_THE_WEEK = (
("SUN", "Sunday"),
           ("MON", "Monday"),
           ("TUE", "Tuesday"),
           ("WED", "Wednesday"),
           ("THURS", "Thursday"),
           ("FRI", "Friday"),
           ("SAT", "Saturday"),
)

# Declaring a Days Model
class DaysOfTheWeek(models.Model):
DaysOfWeek = models.CharField(
max_length = 20,
choices = DAYS_OF_THE_WEEK,
default = 'MON'
)
You can also try this code with Online Python Compiler
Run Code

 

Output

Named groups for organizing data

We have created Django field choices for the form fields in this previous section. We can name the groups. One good advantage of this arrangement is that it gives us a neat way to organize the choices. 

 

Let us see a sample code for this.

FOOD_CHOICES = [
   ("Fruit", (
           ("Apple", "Green Apple"),
           ("Berry", "Blueberry"),
       )
   ),
   ("Vegetable", (
           ("POTATO", "Potato"),
           ("CABBAGE", "Cabbage"),
       )
   ),
]
You can also try this code with Online Python Compiler
Run Code

 

In this code, we have created a group called FOOD_CHOICES and added choices in it in an organized manner. 

 

The first element in each tuple is the name that applies to the group. Here the group names are ‘Fruit’ and ‘Vegetable’. The second element is iterable of 2-tuples, with each 2-tuple containing a value and a human-readable name for an option.

Using Enumeration

Enumeration is an alternative way of defining Django field choices. Enumeration in Python is a set of symbolic names bound to unique constant values. We can use the “enum” module to implement Enumerations in Python.

 

Let us understand how to use Enums through a simple example.

 

Assume there is a field to identify the colour of a crayon, given choices of colours are Red, Blue, Green, and Yellow. Let us define a class for these choices.

 

Code:

from enum import Enum

class ColourChoice(Enum):   # A subclass of Enum
   RD = "Red"
   BL = "Blue"
   GRN = "Green"
   YLW = "Yellow"
You can also try this code with Online Python Compiler
Run Code

 

 

Now let us define our model for these choices.

 

Code:

from django.db import models

class Colour(models.Model):
   title = models.CharField(max_length=255)
   colour = models.CharField(
     max_length=5,
     choices=[(tag, tag.value) for tag in ColourChoice]  # Choices is a list of Tuple
)
You can also try this code with Online Python Compiler
Run Code

 

Output:

 

Advantage of using enums

  • To distinct from any other values within a set of values. 
  • Central Repository having predefined values.
  • Enumeration can be used across our entire program, not just in our models.

Frequently Asked Questions

  1. When should we use Enum as the choice of a field?
    We can use Enum as the choice of a field when we are defining an immutable, related set of constant values which may or may not have a semantic meaning.
     
  2. What is the best way to define choices?
    The best way to define choices is inside a model class and to define a suitably-named constant for each value.

Key Takeaways

In this blog, we have discussed Django Field choices. We have also looked into creating grouped choices and the advantage that they serve. We hope you liked this blog.

Recommended Article:

Live masterclass