我想从django自定义UserCreationForm。我做了以下
class myUserCreationForm(UserCreationForm):
class Meta:
model=User
fields = ('username', 'password1', 'password2')
widgets = {
'username':TextInput(attrs={'class':'form-control'}),
'password':TextInput(attrs={'class':'form-control'}),
'password2':TextInput(attrs={'class':'form-control'}),
}
但它不起作用。渲染模板时创建输入框没有附加表单控件类。可能有什么不对?
答案 0 :(得分:11)
在遇到同样的问题时,我偶然发现了这一点。您可以在myUserCreationForm类上覆盖init方法来设置表单的属性。
class myUserCreationForm(UserCreationForm):
class Meta:
model=User
fields = ('username', 'password1', 'password2')
def __init__(self, *args, **kwargs):
super(myUserCreationForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['password1'].widget.attrs['class'] = 'form-control'
self.fields['password2'].widget.attrs['class'] = 'form-control'
答案 1 :(得分:2)
您需要从sctratch创建表单,它不应该扩展UserCreationForm。 UserCreationForm在其中明确定义了用户名字段以及其他一些字段。你可以看一下here。
答案 2 :(得分:2)
您应该覆盖Meta类以上的字段。这对我有用:
class CustomCreateUserForm(UserCreationForm):
username = forms.RegexField(
label=_("Login"), max_length=30, regex=r"^[\w.@+-]+$",
help_text=_("Required. 30 characters or fewer. Letters, digits and "
"@/./+/-/_ only."),
error_messages={
'invalid': _("This value may contain only letters, numbers and "
"@/./+/-/_ characters.")},
widget=TextInput(attrs={'class': 'form-control',
'required': 'true',
'placeholder': 'Login'
})
)
password1 = forms.CharField(
label=_("Password"),
widget=forms.PasswordInput(attrs={'class': 'form-control',
'required': 'true',
})
)
password2 = forms.CharField(
label=_("Password confirmation"),
widget=forms.PasswordInput(attrs={'class': 'form-control',
'type': 'password',
'required': 'true',
}),
help_text=_("Enter the same password as above, for verification.")
)
first_name = forms.CharField(
label=_("Name"),
widget=forms.TextInput(attrs={'class': 'form-control',
'type': 'text',
'required': 'true',
}),
help_text=_("Enter user first and last name.")
)
email = forms.CharField(
label=_("Email"),
widget=forms.TextInput(attrs={'class': 'form-control',
'type': 'email',
'placeholder': 'Email address',
'required': 'true'
})
)
class Meta:
model = User
答案 3 :(得分:0)
class myUserCreationForm(UserCreationForm):
password1 = forms.CharField(
label='Password',
widget=forms.PasswordInput(attrs={'class': 'form-control'})
)
password2 = forms.CharField(
label='Password',
widget=forms.PasswordInput(attrs={'class': 'form-control'})
)
class Meta:
model = User
fields = ('username', 'password1', 'password2')
widgets = {
'username': TextInput(attrs={'class': 'form-control'}),
# 'password': TextInput(attrs={'class': 'form-control'}), # Remove This Line
# 'password2': TextInput(attrs={'class': 'form-control'}), # Remove This Line
}