在Django中,我具有以下代码,该代码在HTML页面上创建用户名和密码表单:
<div class="control-group"> {{ form.username }} </div> <div class="control-group"> {{ form.password }} </div>
我想在该字段中添加“用户名”和“密码”占位符文本,然后在用户单击该字段时消失。实现此目标的最佳方法是什么?
您必须使用占位符属性
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'
要么
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'}))