从模板中获取 Django 表单小部件的类型 [英] Get type of Django form widget from within template
问题描述
我正在遍历表单的字段,对于某些字段,我想要稍微不同的布局,需要更改 HTML.
I'm iterating through the fields of a form and for certain fields I want a slightly different layout, requiring altered HTML.
为了准确地做到这一点,我只需要知道小部件类型.它的类名或类似的东西.在标准 python 中,这很容易!field.field.widget.__class__.__name__
To do this accurately, I just need to know the widget type. Its class name or something similar. In standard python, this is easy! field.field.widget.__class__.__name__
很遗憾,您不能访问模板中的下划线变量.太棒了!
Unfortunately, you're not allowed access to underscore variables in templates. Great!
您可以测试 field.field.widget.input_type
但这仅适用于文本/密码 类型.我需要更多的解决方案.
You can test field.field.widget.input_type
but this only works for text/password <input ../>
types. I need more resolution that that.
对我来说,无论看起来多么困难,在模板级别执行此操作是最有意义的.我已经将处理字段 HTML 的代码外包给一个单独的模板,该模板包含在字段循环中.这意味着它在 ModelForm
s 和标准 Form
s 之间是一致的(如果我编写了一个中间 Form 类就不会如此).
To me, however difficult it might look, it makes most sense to do this at template level. I've outsourced the bit of code that handles HTML for fields to a separate template that gets included in the field-loop. This means it is consistent across ModelForm
s and standard Form
s (something that wouldn't be true if I wrote an intermediary Form class).
如果你能看到一种不需要我编辑 20 多个表单的通用方法,也请告诉我!
If you can see a universal approach that doesn't require me to edit 20-odd forms, let me know too!
推荐答案
从 Django 1.11 开始,您可以只使用 widget.input_type
.示例:
As of Django 1.11, you can just use widget.input_type
. Example:
{% for field in form.visible_fields %}
<input type="{{ field.field.widget.input_type }}"
id="{{ field.id_for_label }}"
name="{{ field.html_name }}"
placeholder="{{ field.label }}"
maxlength="{{ field.field.max_length }}" />
{% endfor %}
这篇关于从模板中获取 Django 表单小部件的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!