python / beginner
Snippet
Using Choices for Model Fields
The 'choices' attribute limits a field's valid input to a specific list of options, which Django automatically renders as a dropdown menu in forms.
snippet.py
1
2
3
4
5
6
7
8
from django.db import modelsclass Ticket(models.Model):STATUS_CHOICES = [('OPEN', 'Open'),('CLOSED', 'Closed'),]status = models.CharField(max_length=6, choices=STATUS_CHOICES)
django
Breakdown
1
STATUS_CHOICES = [...]
A list of tuples where the first element is stored in the DB and the second is the human-readable name.
2
choices=STATUS_CHOICES
Tells Django to use the predefined list for this field's options.