Open In App

How to use Django Field Choices ?

Last Updated : 17 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Django’s choices option lets you limit a model field to a fixed set of values. It helps keep your data clean and consistent, and automatically shows a dropdown menu in forms and the admin instead of a text box.

Choices are defined as pairs: the first value is saved to the database, and the second is shown to users. For example:

# Format: (value_saved, label_shown)

[

('A', 'Option A'),

('B', 'Option B'),

]

Features of Using Choices

  • Enforces data validation.
  • Restricts user input to predefined values.
  • Automatically renders a <select> dropdown in Django forms and admin.
  • Improves consistency and user experience.

Example: Semester Choices

Suppose we want to restrict a student's semester field to only allow values from 1 to 8. Here’s how we can implement this in Django:

Step 1: Define the Choices (in models.py)

Python
from django.db import models

SEMESTER_CHOICES = [
    ("1", "1"),
    ("2", "2"),
    ("3", "3"),
    ("4", "4"),
    ("5", "5"),
    ("6", "6"),
    ("7", "7"),
    ("8", "8"),
]

Step 2: Use Choices in the Model Field (in models.py)

Python
class Student(models.Model):
    semester = models.CharField(
        max_length=2,
        choices=SEMESTER_CHOICES,
        default="1"
    )

    def __str__(self):
        return f"Semester: {self.get_semester_display()}"

Explanation:

  • choices=SEMESTER_CHOICES restricts the field to the listed values.
  • default="1" sets the default semester to 1.
  • get_semester_display() retrieves the human-readable value.

Let us check in admin panel how semester is created.

django-field-choices

Grouping Choices

Django also supports grouped choices for better organization. Each group has a label and a set of related options.

In your app's model.py we can add the following code for demonstration:

MEDIA_CHOICES = [

('Audio', [

('vinyl', 'Vinyl'),

('cd', 'CD'),

]),

('Video', [

('vhs', 'VHS Tape'),

('dvd', 'DVD'),

]),

('unknown', 'Unknown'),
]

We can then use it like this:

Python
class Media(models.Model):
    media_type = models.CharField(
        max_length=10,
        choices=MEDIA_CHOICES,
        default='unknown'
    )
    def __str__(self):
        return f"{self.get_media_type_display()}"

Grouped choices improve UX in long lists by categorizing options under headings.

Output in the admin panel:

django09
Snapshot of the dropdown menu of Media

Practice Tags :

Similar Reads