Django’s ChoiceField simplifies option selection in forms and the admin interface by allowing you to define pre-defined options for a field. You can define choices by creating a list of two-element tuples for each choice, where the first element represents the actual value stored in the database, and the second element is the human-readable label displayed to users.
models.py
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
STATUS_CHOICES = (
('available', 'Available'),
('out_of_stock', 'Out of Stock'),
('discontinued', 'Discontinued'),
)
status = models.CharField(
max_length=20, choices=STATUS_CHOICES, default='available')
def __str__(self):
return self.name
Django 5 Forms and Admin
Using ChoiceField in Django automatically creates a dropdown widget in forms. In the admin, a dropdown menu is displayed for selecting choices. To handle choice values, use appropriate data types and set blank=True for optional fields. Override the default widget to use a different one. For Django 5.0+, define choice groups for better organization.
class Task(models.Model):
PRIORITY_CHOICES = (
('low', 'Low'),
('medium', 'Medium'),
('high', 'High'),
)
STATUS_CHOICES = (
('pending', 'Pending'),
('in_progress', 'In Progress'),
('completed', 'Completed'),
)
priority = models.CharField(max_length=10, choices=PRIORITY_CHOICES)
status = models.CharField(max_length=15, choices=STATUS_CHOICES)
# Using choice field groups (Django 5.0+)
CATEGORY_CHOICES = {
'urgency': PRIORITY_CHOICES,
'completion': STATUS_CHOICES,
}
category = models.CharField(
max_length=20, choices=CATEGORY_CHOICES.items())
Please take note that it is necessary to add register models in admin.py.
admin.py
from .models import Product, Task
admin.site.register(Product)
admin.site.register(Task)
Saim
Hi there! My name is Saim and I’m excited to dive headfirst into the world of Python Django. I’m eager to learn and grow every step of the way, and I’ll be documenting my journey through blog posts. I’ll share the highs, lows, and everything in between with you. Together, let’s uncover the wonders of Python Django and its endless possibilities in web development.