Django templates: verbose version of a choice

前端 未结 8 1115
野性不改
野性不改 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:19

    Add to your models.py one simple function:

    def get_display(key, list):
        d = dict(list)
        if key in d:
            return d[key]
        return None
    

    Now, you can get verbose value of choice fields like that:

    class MealOrder(models.Model):
        meal = models.CharField(max_length=8, choices=CHOICES)
    
        def meal_verbose(self):
            return get_display(self.meal, CHOICES)    
    

    Upd.: I'm not sure, is that solution “pythonic” and “django-way” enough or not, but it works. :)

    0 讨论(0)
  • 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 }}
    
    0 讨论(0)
  • 2020-11-30 18:28

    I don't think there's any built-in way to do that. A filter might do the trick, though:

    @register.filter(name='display')
    def display_value(bf):
        """Returns the display value of a BoundField"""
        return dict(bf.field.choices).get(bf.data, '')
    

    Then you can do:

    {% for field in form %}
        <tr>
            <th>{{ field.label }}:</th>
            <td>{{ field.data|display }}</td>
        </tr>
    {% endfor %}
    
    0 讨论(0)
  • 2020-11-30 18:31

    In Django templates you can use the "get_FOO_display()" method, that will return the readable alias for the field, where 'FOO' is the name of the field.

    Note: in case the standard FormPreview templates are not using it, then you can always provide your own templates for that form, which will contain something like {{ form.get_meal_display }}.

    0 讨论(0)
  • 2020-11-30 18:37

    You have Model.get_FOO_display() where FOO is the name of the field that has choices.

    In your template do this :

    {{ scoop.get_flavor_display }}
    
    0 讨论(0)
  • 2020-11-30 18:39

    The best solution for your problem is to use helper functions. If the choices are stored in the variable CHOICES and the model field storing the selected choice is 'choices' then you can directly use

     {{ x.get_choices_display }}
    

    in your template. Here, x is the model instance. Hope it helps.

    0 讨论(0)
提交回复
热议问题