python 在 Django 中禁用文本字段的自动完成功能?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2580955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:59:19  来源:igfitidea点击:

Disable autocomplete on textfield in Django?

pythondjangoformsautocomplete

提问by tau-neutrino

Does anyone know how you can turn off autocompletion on a textfield in Django?

有谁知道如何关闭 Django 中文本字段的自动完成功能?

For example, a form that I generate from my model has an input field for a credit card number. It is bad practice to leave autocompletion on. When making the form by hand, I'd add a autocomplete="off" statement, but how do you do it in Django and still retain the form validation?

例如,我从模型生成的表单有一个信用卡号输入字段。保持自动完成是不好的做法。手工制作表单时,我会添加一个 autocomplete="off" 语​​句,但是您如何在 Django 中执行此操作并仍然保留表单验证?

回答by BJ Homer

In your form, specify the widget you want to use for the field, and add an attrsdictionary on that widget. For example (straight from the django documentation):

在您的表单中,指定要用于该字段的小部件,并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'}))

Just add 'autocomplete'='off'to the attrs dict.

只需添加'autocomplete'='off'到 attrs 字典。

回答by jjlorenzo

Add the autocomplete="off" to the form tag, so you don't have to change the django.form instance.

将 autocomplete="off" 添加到表单标记中,这样您就不必更改 django.form 实例。

<form action="." method="post" autocomplete="off"> {{ form }} </form>

<form action="." method="post" autocomplete="off"> {{ form }} </form>

回答by ChillarAnand

If you are defining your own forms, you can add attributes to your fields in the form.

如果您要定义自己的表单,则可以向表单中的字段添加属性。

class CommentForm(forms.Form):
    name = forms.CharField(widget=forms.TextInput(attrs={
        'autocomplete':'off'
    }))

If you are using modelforms, you won't have the luxury of defining field attributes in the form. However, you can use __init__to add required attributes.

如果您使用模型表单,您将无法在表单中定义字段属性。但是,您可以使用__init__添加必需的属性。

class CommentForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(CommentForm, self).__init__(*args, **kwargs)
        self.fields['name'].widget.attrs.update({
            'autocomplete': 'off'
        })

You can also add attributes from Meta

您还可以从 Meta

class CommentForm(forms.ModelForm):
    class Meta:
        widgets = {
            'name': TextInput(attrs={'autocomplete': 'off'}),
        }

回答by Bartosz

For me adding extra attribute in templates also worked:

对我来说,在模板中添加额外的属性也有效:

`<form method="POST", autocomplete="off">
    {% csrf_token %}
    {{ form.as_p }}`