Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable autocomplete on textfield in Django?

Does anyone know how you can turn off autocompletion on a textfield in 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?

like image 559
tau-neutrino Avatar asked Apr 05 '10 20:04

tau-neutrino


People also ask

How to Disable autocomplete in Django forms?

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

What is widget in Django?

A widget is Django's representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget. The HTML generated by the built-in widgets uses HTML5 syntax, targeting <!


2 Answers

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.

like image 185
BJ Homer Avatar answered Sep 18 '22 21:09

BJ Homer


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>

like image 23
jjlorenzo Avatar answered Sep 17 '22 21:09

jjlorenzo