Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin panel can not set valid choice when choices are enum.Enum

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]  
    )
like image 314
vvoody Avatar asked Jun 21 '18 17:06

vvoody


2 Answers

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]  
    )
like image 78
Dalvtor Avatar answered Nov 06 '22 21:11

Dalvtor


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()]  
    )
like image 35
jrief Avatar answered Nov 06 '22 21:11

jrief