Get type of Django form widget from within template

前端 未结 6 1513
你的背包
你的背包 2020-12-01 01:27

I\'m iterating through the fields of a form and for certain fields I want a slightly different layout, requiring altered HTML.

To do this accurately, I just need to

6条回答
  •  长情又很酷
    2020-12-01 02:09

    Making a template tag might work? Something like field.field.widget|widget_type

    Edit from Oli: Good point! I just wrote a filter:

    from django import template
    register = template.Library()
    
    @register.filter('klass')
    def klass(ob):
        return ob.__class__.__name__
    

    And now {{ object|klass }} renders correctly. Now I've just got to figure out how to use that inside a template's if statement.

    Edit from Oli #2: I needed to use the result of that in an if statetement in-template, so I just shifted all that logic into the templatetag. Magic. Thanks for poking me in the right direction.

提交回复
热议问题