django add placeholder text to form field

Viewed 15412

In Django I have the below code which is creating a username and password form on an HTML Page:

<div class="control-group">
    {{ form.username }}
</div>
<div class="control-group">
    {{ form.password }}
</div>

I want to add "Username" and "Password" placeholder text within the field, and then when the user clicks on the field the word dissapears. What is the best way to achieve this ?

4 Answers

In case if you want to have field name as a placeholder, you can use code below:

class LoginForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(LoginForm, self).__init__(*args, **kwargs)
        for k,v in self.fields.items():
            v.widget.attrs['placeholder'] = k.capitalize()

Otherwise please refere to this answer.

Related