python - Django:如何检查字段小部件是否是模板中的复选框?

标签 python django django-forms django-templates

我创建了一个用于呈现表单字段的自定义模板:

<tr class="{{field.field.widget.attrs.class}}">
    <th class="label">
        <label for="{{field.auto_id}}">
            {{field.label}}
            {% if not field.field.required %}<span class="optional">(optional)</span>{% endif %}
        </label>
    </th>
    <td class="field">
        {{field}}
        {% if field.errors %}<label class="error" for="{{field.auto_id}}">{{field.errors.0}}</label>{% endif %}
        {% if field.help_text %}<small class="help-text">{{field.help_text}}</small>{% endif %}
    </td>
</tr>

但我想检查小部件是否是一个复选框,如果是,则以不同的方式呈现它。我怎样才能在模板中做到这一点?

最佳答案

使用 custom template filter!
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__
在您的模板中:
{% load my_custom_tags %}
 
{% if field|is_checkbox %}
  do something
{% endif %}
关于实现的旁注:当我不实例化 CheckboxInput 时,类名是 MediaDefiningClass。
>>> form django.forms import CheckboxInput
KeyboardInterrupt
>>> CheckboxInput.__class__.__name__
'MediaDefiningClass'

关于python - Django:如何检查字段小部件是否是模板中的复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3927018/

相关文章:

python - 在 Django View 中结合 modelformset 和 inlineformset

python - ElasticSearch 匹配查询得分

python - Django - 在结果页面的搜索框中显示查询

python - 数据抓取器 : the contents of the div tag is empty (? ?)

database - heroku部署的django app DATABASES设置问题

jquery - AJAX 函数未获取 id

Django 表单更改密码

python - 运行Django-Viewflow更新节点?

django - DRF : static/read-only/non-model fields in serializers?

python - Django 序列化器 : validate function not called