Django-Allauth中的自定义表单验证

7

我希望在django-allauth中对字段进行额外的验证。例如,我想防止使用免费电子邮件地址。因此,我想在注册时运行此方法。

def clean_email(self):
    email_domain = self.cleaned_data['email'].split('@')[1]
    if email_domain in self.bad_domains:
        raise forms.ValidationError(_("Registration using free email addresses is prohibited. Please supply a different email address."))

同样,我想在除电子邮件地址以外的不同字段上运行自定义验证。我该如何执行此操作?
1个回答

7

在allauth配置中有一些适配器。例如这个:

ACCOUNT_ADAPTER (="allauth.account.adapter.DefaultAccountAdapter")
    Specifies the adapter class to use, allowing you to alter certain default behaviour.

您可以通过覆盖默认适配器来指定新适配器。只需覆盖 clean_email 方法。

class MyCoolAdapter(DefaultAccountAdapter):

    def clean_email(self, email):
        """
        Validates an email value. You can hook into this if you want to
        (dynamically) restrict what email addresses can be chosen.
        """
        *** here goes your code ***
        return email

然后修改settings.py文件中的ACCOUNT_ADAPTER

ACCOUNT_ADAPTER = '**app**.MyCoolAdapter'

请查看默认行为: https://github.com/pennersr/django-allauth/blob/master/allauth/account/adapter.py


1
要拒绝一个电子邮件地址,请引发 django.forms.ValidationError 异常。 - Flimm
1
如何在另一个表单字段上执行此操作? - Hakim
如果电子邮件被拒绝,应该返回什么? - filiphl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接