[Django]-Disable autocomplete on textfield in Django?

36πŸ‘

βœ…

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

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.

πŸ‘€BJ Homer

37πŸ‘

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

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

πŸ‘€jjlorenzo

13πŸ‘

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.

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

class CommentForm(forms.ModelForm):
    class Meta:
        widgets = {
            'name': TextInput(attrs={'autocomplete': 'off'}),
        }
πŸ‘€Chillar Anand

1πŸ‘

For me adding extra attribute in templates also worked:

<form method="POST", autocomplete="off">
    {% csrf_token %}
    {{ form.as_p }}`
πŸ‘€Bartosz

0πŸ‘

if you are using django inbuilt forms for example login forms, or usercreationform as opposed to your own custom model forms, then you will have to remove autocomplete in javascript

const username = document.getElementById("id_username");
username.autocomplete = "off"
πŸ‘€Abdoolkareem

Leave a comment