JackLeo
JackLeo

Reputation: 4740

How do I set custom HTML attributes in django forms?

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'

Upvotes: 23

Views: 41457

Answers (4)

Don
Don

Reputation: 17636

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.

Upvotes: 11

John Lehmann
John Lehmann

Reputation: 8225

There's also the template-only solution using a filter. I recommend django-widget-tweaks:

{% load widget_tweaks %}

{{ form.email|attr:'required:true' }}

Upvotes: 9

webtweakers
webtweakers

Reputation: 745

Old question, but for who-ever is looking for another alternative, there's also this: https://docs.djangoproject.com/en/1.6/topics/forms/modelforms/#overriding-the-default-fields

You can do something like this:

from django.forms import ModelForm, Textarea
from myapp.models import Author

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title', 'birth_date')
        widgets = {
            'name': Textarea(attrs={'cols': 80, 'rows': 20}),
        }

Upvotes: 8

mcanterb
mcanterb

Reputation: 619

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',})

Upvotes: 29

Related Questions