django add placeholder text to form field
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'}))
In case it might help someone, 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 = (...)
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'}),
..........
}