问题描述
我尝试通过4个字段在注册表单中启用占位符:电话,电子邮件,password1,password2。对于前两个字段都正确,但对于密码字段则不起作用。
I try to enable placeholder at my SignUp form with 4 fields: phone, email, password1, password2. For first two fields all correct, but for password field it doesn't work.
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from customuser.models import User
from django.forms import TextInput,EmailInput,PasswordInput
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ('phone', 'email', 'password1', 'password2', 'is_client','is_partner')
widgets = {
'email': EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email adress'}),
'phone': TextInput(attrs={'class': 'form-control', 'placeholder': 'Phone number +79011234567'}),
'password1': PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password from numbers and letters of the Latin alphabet'}),
'password2': PasswordInput(attrs={'class': 'form-control', 'placeholder': '
Password confirmation'}),
}
推荐答案
Meta.widgets
选项不适用于在表单中声明的字段。请参阅文档中的注释。在这种情况下,在 UserCreationForm
password1 和 password2
>(它们不是模型字段),因此您不能在 widgets
中使用它们。
The Meta.widgets
option doesn't apply to fields that were declared in the form. See the note in the docs. In this case, password1
and password2
are declare on the UserCreationForm
(they aren't model fields), therefore you can't use them in widgets
.
您可以在 __ init __
方法中设置小部件:
You could set the widget in the __init__
method instead:
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ('phone', 'email', 'is_client', 'is_partner')
widgets = {
'email': EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email adress'}),
'phone': TextInput(attrs={'class': 'form-control', 'placeholder': 'Phone number +79011234567'}),
}
def __init__(self, *args, **kwargs):
super(SignUpForm, self).__init__(*args, **kwargs)
self.fields['password1'].widget = PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password from numbers and letters of the Latin alphabet'})
self.fields['password2'].widget = PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password confirmation'})
这篇关于Django密码字段占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!