Django – Textchoices and admin.site.register

Question:

I have a choice class TextChoices:

class Category(models.TextChoices):
    vegetable = 'VEG', 'vegetable'
    fruit = 'FRT', 'fruit'
    carbs = 'CRB', 'carbs'
    fish = 'FSH', 'fish'
    meat = 'MT', 'meat'
    sweet = 'SWT', 'sweet'
    dairy = 'DRY', 'dairy'
    ready = 'RDY', 'ready'

    # def __str__(self):
    #     return self.name
    def __str__(self):
        return self.choices

Used in:

class Fooditem(models.Model):

    name = models.CharField(max_length=200)
    #    category = models.ManyToManyField(Category)
    category = models.CharField(max_length=3, choices=Category.choices, default=Category.vegetable)

Now, I would like to make Category editable by admin:

admin.site.register(Category)

But I have the following error:

  File "PycharmProjectsCalories_NewFityfeedadmin.py", line 14, in <module>
    admin.site.register(Category)
  File "PycharmProjectsCalories_Newvenvlibsite-packagesdjangocontribadminsites.py", line 106, in register
    if model._meta.abstract:
AttributeError: 'Category' object has no attribute '_meta'

I am relatively new in Django and would appreciate your help, also in understanding
how I can solve these problems myself (struggling with reference documentation).

Asked By: dbidinost

||

Answers:

Since categories can be added dynamically it should be a Model:

class Category(models.Model):
    name = models.CharField(max_length=35)

Next to make the relationship between Category and Fooditem you want to use a ForeignKey [Django docs]:

class Fooditem(models.Model):
    name = models.CharField(max_length=200)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="food_items")

To access a Food items category:

print(food_item_instance.category.name) # Outputs "vegetable" or whatever the category is.

Also to get each food item in a category:

food_items = category_instance.food_items.all()

Now you can register Category to the admin site since it is a model.

Answered By: Abdul Aziz Barkat
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.