Django-registration 如何检查用户是否存在

Django-registration how to check if user exists

我正在使用 Django-registration 和 Django 1.8.15 来注册用户。我的 urls.py 看起来像这样:

from registration.backends.hmac.views import RegistrationView

url(r'^registration/register/$', RegistrationView.as_view(form_class=MyCustomSubscriberForm), name="registration_register"),

这基本上是我提供表格和模板的 CBV。 这是表格:

class MyCustomSubscriberForm(RegistrationForm):

class Meta:
    model = MyCustomSubscriber
    fields = ('firstname', 'surname', 'email', ) 

我的问题是如何处理此 CBV 中的验证?

目前,如果有人试图用一个已经使用过的电子邮件地址注册 Django 给出了 IntegrityError at /registration/register/ ...

使用 Validators from Django-registrations 的最佳方法是什么?例如 - 我如何确保如果某个电子邮件用户已经存在,该用户会在模板中收到通知?

如何使用 Django-Registration 已经提供的验证器扩展此 CBV 或处理我的代码中的此错误?

您需要在表单的 clean_<field> 方法中验证电子邮件,如果它是您可以在模板中呈现的重复电子邮件,则引发错误。

请查看文档中的这一部分:Cleaning a specific field attribute

因此您可以使用如下代码:

def clean_email(self):
    data = self.cleaned_data['email']
    duplicate_users = User.objects.filter(email=data)
    if self.instance.pk is not None:  # If you're editing an user, remove him from the duplicated results
        duplicate_users = duplicate_users.exclude(pk=self.instance.pk)
    if duplicate_users.exists():
        raise forms.ValidationError("E-mail is already registered!")
    return data

在更仔细地研究 Django-registration 之后,我发现 Django-registration 已经以其形式之一实现了此功能:RegistrationFormUniqueEmail,它是 RegistrationForm 的子类。

为了使用它,我只需要像这样在我的表单中对其进行子类化:

class MyCustomSubscriberForm(RegistrationFormUniqueEmail):

    def __init__(self, *args, **kwargs):
        super (RegistrationFormUniqueEmail, self).__init__(*args, **kwargs)

   class Meta: 
      model = get_user_model()
      fields = ('firstname', 'lastname', 'email') 

就是这样 - 表单正在检查所提供的电子邮件地址是否唯一。