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

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

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


    
        <         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-04 20:32

    It is kind of late to answer, but I implemented something similar to what is done in Django's admin.

    First, I added a new attribute is_checkbox to the Field class:

    # forms.py
    from django import forms
    from django.forms.fields import Field
    setattr(Field, 'is_checkbox', lambda self: isinstance(self.widget, forms.CheckboxInput ))
    

    Then, I can easily detect a CheckboxInput widget in the template. Here is an example to render checkboxes to the left and other widgets to the right:

    {% if field.field.is_checkbox %}
        {{ field }} {{ field.label_tag }}
    {% else %}
        {{ field.label }} {{ field }}
    {% endif %}
    

提交回复
热议问题