I use enum.Enum as choices for field language.
I can create a book by b = Book(title="Some Title", language=LanguageChoice.EN)
.
And query by books = Book.objects.filter(languge=LanguageChoice.EN)
.
However, when I want to create new books at admin panel, it says Select a valid choice. LanguageChoice.EN is not one of the available choices.
.
Django has ability to serialize enum.Enum since 1.10. So how should admin panel work? Thanks.
from enum import Enum
from django.db import models
class LanguageChoice(Enum):
DE = "German"
EN = "English"
CN = "Chinese"
ES = "Spanish"
class Book(models.Model):
title = models.CharField(max_length=255)
language = models.CharField(
max_length=5,
choices=[(tag, tag.value) for tag in LanguageChoice]
)
I just had this problem. Rewrite your Book
model as the following, and notice the change in the choices line.
class Book(models.Model):
title = models.CharField(max_length=255)
language = models.CharField(
max_length=5,
choices=[(tag.name, tag.value) for tag in LanguageChoice]
)
You should rewrite your Django model as
class LanguageChoice(Enum):
DE = "German"
EN = "English"
CN = "Chinese"
ES = "Spanish"
@classmethod
def all(self):
return [LanguageChoice.DE, LanguageChoice.EN, LanguageChoice.CN, LanguageChoice.ES]
class Book(models.Model):
title = models.CharField(max_length=255)
language = models.CharField(
max_length=5,
choices=[(tag.value, tag.name) for tag in LanguageChoice.all()]
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With