我想知道我是否可以在没有密码确认的情况下制作UseCreationForm(仅限密码1)。代码I使用:
#forms.py
class UserRegistrationForm(UserCreationForm):
email = forms.EmailField(max_length=200, help_text='Required')
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
#views.py
class HomeView(View):
template_name = 'home.html'
def get(self, request):
queryset = Profile.objects.filter(verified=True)
form = UserRegistrationForm()
context = {
'object_list': queryset,
'form':form,
'num_of_users': User.objects.all().count()
}
return render(request, self.template_name, context)
问题是,当我将forms.py作为:
时class UserRegistrationForm(UserCreationForm):
email = forms.EmailField(max_length=200, help_text='Required')
class Meta:
model = User
fields = ('username', 'email', 'password1')
表单也有字段password2。任何解决方案?
答案 0 :(得分:4)
您可以覆盖表单的__init__()
方法并删除所需的字段:
class UserRegistrationForm(UserCreationForm):
email = forms.EmailField(max_length=200, help_text='Required')
class Meta:
model = User
fields = ('username', 'email', 'password1')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
del self.fields['password2']
重要:无论如何,通常只有一个密码字段,因为用户可能会输错。安全级别下降了很多。
答案 1 :(得分:0)
您可以使用“无”值覆盖“ password2”。
class UserRegistrationForm(UserCreationForm):
password2 = None
class Meta:
...