Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set custom HTML attributes in django forms?

Tags:

I have a Django form that is part of page. Lets say I have a field:

search_input = forms.CharField(_(u'Search word'), required=False)

I can access it only in template via {{ form.search_input }}. How to set custom HTML attrs (such as name and value)? I would like to find flexible solution, that would allow me to add any needed custom attributes to all types of fields.

I found https://docs.djangoproject.com/en/dev/ref/forms/widgets/#widget

But using attrs gives me (if used with CharField):

__init__() got an unexpected keyword argument 'attrs'
like image 881
JackLeo Avatar asked Aug 29 '11 14:08

JackLeo


2 Answers

You can change the widget on the CharField to achieve the effect you are looking for.

search_input = forms.CharField(_(u'Search word'), required=False)
search_input.widget = forms.TextInput(attrs={'size': 10, 'title': 'Search',})
like image 165
mcanterb Avatar answered Sep 23 '22 20:09

mcanterb


You can also try this:

search_input = forms.CharField(
    _(u'Search word'),
    required=False,
    widget=forms.TextInput(attrs={'size': 10, 'title': 'Search',})
)

This is documented in the section entitled Styling widget instances.

like image 24
Don Avatar answered Sep 24 '22 20:09

Don