tau*_*ino 18 python forms django autocomplete
有谁知道如何在Django的文本字段中关闭自动完成功能?
例如,我从我的模型生成的表单有一个信用卡号的输入字段.保留自动完成功能是不好的做法.在手工制作表单时,我会添加一个autocomplete ="off"语句,但是如何在Django中执行此操作并仍然保留表单验证?
BJ *_*mer 29
在表单中,指定要用于该字段的窗口小部件,并attrs
在该窗口小部件上添加字典.例如(直接来自django文档):
class CommentForm(forms.Form):
name = forms.CharField(
widget=forms.TextInput(attrs={'class':'special'}))
url = forms.URLField()
comment = forms.CharField(
widget=forms.TextInput(attrs={'size':'40'}))
Run Code Online (Sandbox Code Playgroud)
只需添加'autocomplete'='off'
到attrs dict.
小智 25
将autocomplete ="off"添加到表单标记,因此您不必更改django.form实例.
<form action="." method="post" autocomplete="off">
{{ form }}
</form>
如果要定义自己的表单,则可以将属性添加到表单中的字段。
class CommentForm(forms.Form):
name = forms.CharField(widget=forms.TextInput(attrs={
'autocomplete':'off'
}))
Run Code Online (Sandbox Code Playgroud)
如果您使用的是模型形式,则无法在表单中定义字段属性。但是,您可以使用__init__
添加必需的属性。
class CommentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CommentForm, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update({
'autocomplete': 'off'
})
Run Code Online (Sandbox Code Playgroud)
您还可以从添加属性 Meta
class CommentForm(forms.ModelForm):
class Meta:
widgets = {
'name': TextInput(attrs={'autocomplete': 'off'}),
}
Run Code Online (Sandbox Code Playgroud)