Reputation: 166
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]
)
Upvotes: 6
Views: 2599
Reputation: 3286
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]
)
Upvotes: 4
Reputation: 9
I changed (tag,tag.value)
to (tag.value,tag)
and it worked.
Upvotes: -4
Reputation: 1695
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()]
)
Upvotes: 2