Django: How to check if field widget is checkbox in the template?

前端 未结 3 1898
一向
一向 2021-01-04 20:09

I\'ve created a custom template for rendering form fields:


    
        <         


        
3条回答
  •  情深已故
    2021-01-04 20:09

    Use a custom template filter!

    In yourapp/templatetags/my_custom_tags.py:

    from django import template
    from django.forms import CheckboxInput
    
    register = template.Library()
    
    @register.filter(name='is_checkbox')
    def is_checkbox(field):
      return field.field.widget.__class__.__name__ == CheckboxInput().__class__.__name__
    

    In your template:

    {% load my_custom_tags %}
     
    {% if field|is_checkbox %}
      do something
    {% endif %}
    

    Side note on implementation: when I don't instantiate a CheckboxInput, the class name is MediaDefiningClass.

    >>> form django.forms import CheckboxInput
    KeyboardInterrupt
    >>> CheckboxInput.__class__.__name__
    'MediaDefiningClass'
    

提交回复
热议问题