I’m using Django 4.2 and i was looking for a field to select form a given options. I came across TextChoises but its not showing up in my admin panel. Am i using it the right way?
models.py
class Gallery(models.Model):
id = models.AutoField(primary_key=True)
type = models.TextChoices("Image", "Video")
title = models.CharField(max_length=100,null=True)
file = models.FileField(upload_to='gallery/', null=True)
what i am trying to do is to have two options image or video to choose from.
1 Like
You can use choices attribute in your model fields like:
class MC:
timing = (
('D', "Day"),
('W', "Week"),
('M', "Month")
)
gender = (
(1, "Man"),
(2, "Woman"),
(3, "Agender"),
(4, "Bigender"),
(5, "Genderfluid"),
(6, "Genderqueer"),
(7, "Gender nonconfirming"),
(8, "Gender questioning"),
(9, "Gender variant"),
(10, "Intersex"),
(11, "Neutrois"),
(12, "Nonbinary Man"),
)
class ABC(models.Model):
duration_type = models.CharField(choices=MC().timing, default='M', max_length=3)
gender = models.SmallIntegerField(default=1, choices=MC.gender)
In the above example I’ve given different kinds of choices like with CharField
and SmallIntegerField
.
Yes i get how to use choices with CharField but i wanted to try out or understand TextChoices.
Okay, so take a look at this part of docs Model field reference | Django documentation | Django here you will see how models.TextChoices
are being used.
1 Like
Also, according to your model the updated model from my end should be like this:
class Gallery(models.Model):
class MediaType(models.TextChoices):
IMAGE = 'Image'
VIDEO = 'Video'
id = models.AutoField(primary_key=True)
type = models.CharField(max_length=5, choices=MediaType.choices)
2 Likes