Django templates: verbose version of a choice

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

    Basing on Noah's reply, here's a version immune to fields without choices:

    #annoyances/templatetags/data_verbose.py
    from django import template
    
    register = template.Library()
    
    @register.filter
    def data_verbose(boundField):
        """
        Returns field's data or it's verbose version 
        for a field with choices defined.
    
        Usage::
    
            {% load data_verbose %}
            {{form.some_field|data_verbose}}
        """
        data = boundField.data
        field = boundField.field
        return hasattr(field, 'choices') and dict(field.choices).get(data,'') or data
    

    I'm not sure wether it's ok to use a filter for such purpose. If anybody has a better solution, I'll be glad to see it :) Thank you Noah!

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

    We can extend the filter solution by Noah to be more universal in dealing with data and field types:

    <table>
    {% for item in query %}
        <tr>
            {% for field in fields %}
                <td>{{item|human_readable:field}}</td>
            {% endfor %}
        </tr>
    {% endfor %}
    </table>
    

    Here's the code:

    #app_name/templatetags/custom_tags.py
    def human_readable(value, arg):
        if hasattr(value, 'get_' + str(arg) + '_display'):
            return getattr(value, 'get_%s_display' % arg)()
        elif hasattr(value, str(arg)):
            if callable(getattr(value, str(arg))):
                return getattr(value, arg)()
            else:
                return getattr(value, arg)
       else:
           try:
               return value[arg]
           except KeyError:
               return settings.TEMPLATE_STRING_IF_INVALID
    register.filter('human_readable', human_readable)
    
    0 讨论(0)
提交回复
热议问题