Thursday, May 24, 2012

Adding placeholders, autofocus and other attributes to Django forms

Placeholder is a short hint (a word or short phrase) intended to aid the user with data entry in forms. With HTML5, adding placeholders to forms is as simple as including a keyword:

<label>Name: <input name="name" placeholder="John Doe" type="text" /></label>

This would appear in the form as:


To add placeholders to Django forms, simply specify placeholder as an attribute to the form widget.

  name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'John Doe'})

This is actually a pretty general and useful way of passing attributes to Django forms. We can pass other attributes like 'autofocus':'autofocus'. Autofocus is when we want the form field to be in focus automatically when the page loads.

This is for forms created in our app's own If we want to pass attributes to forms created by a Django package, we have to pass those attributes at the form's init.

Say, to add attributes to a form called RegistrationForm from some Django package with fields username and password, first create a form in project's that inherits RegistrationForm. In the __init__ function of the inherited form, pass all the attributes to the form widgets.

class MyRegistrationForm(RegistrationForm):
    def __init__(self, *args, **kwargs):          
        super(MyRegistrationForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs['placeholder'] = u'Username'
        self.fields['password'].widget.attrs['placeholder'] = u'Password'

Now while using the form, use it as
form = MyRegistrationForm()

This will display base form with the attributes passed to to it at init.

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog.
    Really very informative post you shared here. Kindly keep blogging.
    If anyone wants to become a Front end developer learn from Javascript Online Training from India .
    or learn thru JavaScript Online Training from India.
    Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai