6

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 ?

Jaron787
  • 562
  • 1
  • 11
  • 29
  • 2
    Possible duplicate of [How do I add a placeholder on a CharField in Django?](https://stackoverflow.com/questions/4101258/how-do-i-add-a-placeholder-on-a-charfield-in-django) – doru May 23 '17 at 11:37

4 Answers4

14

You must use the placeholder properties

class LoginForm(forms.Form):
    username = forms.CharField(label='username')
    password = forms.CharField(label='password')


    def __init__(self, *args, **kwargs):
        super(LoginForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs['placeholder'] = 'username'
        self.fields['password '].widget.attrs['placeholder'] = 'password'

or

class LoginForm(forms.Form):
    username = forms.CharField(label='username',widget=forms.TextInput(attrs={'placeholder':'username'}))
    password = forms.CharField(label='password',widget=forms.PasswordInput(attrs={'placeholder':'password'}))
aziminia
  • 449
  • 1
  • 5
  • 15
9

I wanted to use the help_text property of a model as the placeholder. This is the simplest way I could figure it out, based on aziminia's answer:

class MyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for _, value in self.fields.items():
            value.widget.attrs['placeholder'] = value.help_text

    class Meta:
        model = models.MyModel
        fields = (...)
halfer
  • 19,824
  • 17
  • 99
  • 186
martinarroyo
  • 9,389
  • 3
  • 38
  • 75
4

I hope you do have a forms.py file in your project. While creating your form, you can use following to set placeholder for your fields:

username = forms.CharField(label='username', 
                widget=forms.TextInput(attrs={'placeholder': 'username'}))

If you have ModelForm in your project you can implement as:

 class MyForm(forms.ModelForm):
    class Meta:
        model = User
        widgets = {
            'username': forms.TextInput(attrs={'placeholder': 'username'}),
             ..........
        }
Sijan Bhandari
  • 2,941
  • 3
  • 23
  • 36
0

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.

Rashid Mahmood
  • 313
  • 4
  • 10