Django templates: verbose version of a choice

前端 未结 8 1150
野性不改
野性不改 2020-11-30 18:16

I have a model:

from django.db import models

CHOICES = (
    (\'s\', \'Glorious spam\'),
    (\'e\', \'Fabulous eggs\'),
)

class MealOrder(models.Model):
          


        
8条回答
  •  天涯浪人
    2020-11-30 18:25

    My apologies if this answer is redundant with any listed above, but it appears this one hasn't been offered yet, and it seems fairly clean. Here's how I've solved this:

    from django.db import models
    
    class Scoop(models.Model):
        FLAVOR_CHOICES = [
            ('c', 'Chocolate'),
            ('v', 'Vanilla'),
        ]
    
        flavor = models.CharField(choices=FLAVOR_CHOICES)
    
        def flavor_verbose(self):
            return dict(Scoop.FLAVOR_CHOCIES)[self.flavor]
    

    My view passes a Scoop to the template (note: not Scoop.values()), and the template contains:

    {{ scoop.flavor_verbose }}
    

提交回复
热议问题