A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/how-to-use-django-field-choices/ below:

How to use Django Field Choices ?

How to use Django Field Choices ?

Last Updated : 17 May, 2025

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 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:

Let us check in admin panel how semester is created.

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:

Snapshot of the dropdown menu of Media

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4