在您的情况下,您可以使用一个表单和一个视图。此表单检查电子邮件是否存在,如果存在,则引发 ValidationsError
class LoginOrSignupForm(forms.ModelForm):
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput(render_value=False))
def clean_email(self):
existing = User.objects.filter(email__iexact=self.cleaned_data['email'], username__iexact=self.cleaned_data['email'])
if existing.exists():
raise forms.ValidationError(_("A user with this e-mail already exists."))
return self.cleaned_data['email']
然后在你看来
if form.is_valid():
#signup
elif form['email'].errors and form['email'].errors[0] == _("A user with this e-mail already exists."):
#login
user = auth.authenticate(username=form['email'].value(), password=form['password'].value())
auth.login(request, user)
该解决方案在基于功能的视图中工作。因此,对于您想要使用 CBV 的情况,我们可以在您的 CBV 中覆盖 form_invalid 方法:
def form_invalid(self, form):
if form['email'].errors and form['email'].errors[0] == _("A user with this e-mail already exists."):
user = auth.authenticate(username=form['email'].value(), password=form['password'].value())
auth.login(request, user)
return HttpRedirect('your page')
return super(YouViewName, self).form_invalid(form)
对于 form_valid 我们不需要覆盖它,只要记住如果你的表单是有效的,它应该注册一个新用户。在这种情况下,adjango.views.generic.CreateView
可以提供帮助。