如何让Django表单显示html必需属性? [英] How do I get Django forms to show the html required attribute?
本文介绍了如何让Django表单显示html必需属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个表单字段:
email = forms.EmailField(
required=True,
max_length=100,
)
它具有必需的属性,但在html中没有添加html属性需要
。事实上,它甚至不使用电子邮件
作为字段类型,它使用文本
...虽然它似乎获得max_length
It has the required attribute, but in the html it is not adding the html attribute required
. In fact it's not even using email
as the field type, it's using text
... though it appears to get max_length just fine.
实际:
<input id="id_email" type="text" name="email" maxlength="100">
预期:
<input id="id_email" type="email" name="email" maxlength="100" required="true">
如何让Django在html表单中使用正确的属性?
How can I get Django to use the correct attributes in html forms?
推荐答案
Monkeypatching Widget是你最好的选择:
Monkeypatching Widget is your best bet:
from django.forms.widgets import Widget
from django.contrib.admin.widgets import AdminFileWidget
from django.forms import HiddenInput, FileInput
old_build_attrs = Widget.build_attrs
def build_attrs(self, extra_attrs=None, **kwargs):
attrs = old_build_attrs(self, extra_attrs, **kwargs)
# if required, and it's not a file widget since those can have files
# attached without seeming filled-in to the browser, and skip hidden "mock"
# fileds created for StackedInline and TabbedInline admin stuff
if (self.is_required
and type(self) not in (AdminFileWidget, HiddenInput, FileInput)
and "__prefix__" not in attrs.get("name", "")):
attrs['required'] = 'required'
return attrs
Widget.build_attrs = build_attrs
这篇关于如何让Django表单显示html必需属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文