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.
Read More

Wednesday, May 23, 2012

Changing Django Password

Go to the directory where your resides:

$ python shell
>>from django.contrib.auth.models import User
>> users = User.objects.all()
>> users
(output) [<User: foo>, <User: adminlogin>, <User: bar>]
>> user = User.objects.filter(name='adminlogin')
>> user.set_password('newpassword')

This can be used to do most user object management.
Read More