Django choices in Admin when Enum is used

2948 views python
2

I have a model where I am using Enum for choices:

class Agreement(models.Model):
    class Category(enum.Enum):
        EULA = 0
        PROVIDER = 1

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    category = models.IntegerField(
        choices=[(choice.name, choice.value)
                 for choice in Category])
    title = models.CharField(max_length=128)
    content = models.TextField()

I register it using simple admin site registration:

admin.site.register(Agreement)

When admin site renders the object it doesn't allow me to save it? Has anyone had a similar issue?

enter image description here

answered question

1 Answer

0

According to the documentation:

The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name.

name and value should be the other way around, like this:

category = models.IntegerField(
    choices=[(choice.value, choice.name)
             for choice in Category])

because category is an integer field and name returns a string.

posted this

Have an answer?

JD

Please login first before posting an answer.