Django: How do I add arbitrary html attributes to input fields on a form?
If you are using "ModelForm":
class YourModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(YourModelForm, self).__init__(*args, **kwargs)
self.fields['city'].widget.attrs.update({
'autocomplete': 'off'
})
Check this page
city = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off'}))
If you are using ModelForm
, apart from the possibility of using __init__
as @Artificioo provided in his answer, there is a widgets
dictionary in Meta for that matter:
class AuthorForm(ModelForm):
class Meta:
model = Author
fields = ('name', 'title', 'birth_date')
widgets = {
'name': Textarea(attrs={'cols': 80, 'rows': 20}),
}
Relevant documentation
Sorry for advertisment, but I've recently released an app (https://github.com/kmike/django-widget-tweaks) that makes such tasks even less painful so designers can do that without touching python code:
{% load widget_tweaks %}
...
<div class="field">
{{ form.city|attr:"autocomplete:off"|add_class:"my_css_class" }}
</div>
or, alternatively,
{% load widget_tweaks %}
...
<div class="field">
{% render_field form.city autocomplete="off" class+="my_css_class" %}
</div>