Django:如何检查字段小部件是否在模板中复选框? [英] Django: How to check if field widget is checkbox in the template?
本文介绍了Django:如何检查字段小部件是否在模板中复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经创建了一个用于呈现表单字段的自定义模板:
I've created a custom template for rendering form fields:
<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>
但是我想检查窗口小部件是否是复选框,如果是,则渲染不同。如何在模板中执行?
But I want to check if the widget is a checkbox, and if so, render it differently. How can I do that in the template?
推荐答案
使用自定义模板过滤器
在 yourapp / templatetags / my_custom_tags.py
:
from django import template
from django.forms import CheckboxInput
@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。 / p>
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'
这篇关于Django:如何检查字段小部件是否在模板中复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文