To create a Django model with a SlugField
and choices option, you can define the model class and specify the choices for the field. Here's an example:
pythonfrom django.db import models
class MyModel(models.Model):
# Define choices for the field
CHOICES = (
('choice1', 'Choice 1'),
('choice2', 'Choice 2'),
('choice3', 'Choice 3'),
)
# Define the SlugField with choices option
my_field = models.SlugField(choices=CHOICES, unique=True)
# Other fields of the model
other_field = models.CharField(max_length=100)
In this example:
MyModel
.my_field
is a SlugField
that accepts choices specified in the CHOICES
tuple.unique=True
parameter ensures that each slug value within the field is unique.'choice1'
, 'choice2'
, etc., with whatever values you need for your choices.other_field
is just a placeholder for other fields you might have in your model.With this setup, when you create forms for your model or interact with the model in Django admin, you'll get a dropdown or select input for my_field
with the choices you specified. The selected value will be stored as a slug value corresponding to the choice made.