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

Cra*_*igH 7 django-allauth

我想对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."))
Run Code Online (Sandbox Code Playgroud)

同样,我想在电子邮件地址以外的其他字段上运行自定义验证.我怎么能这样做?

jor*_*gos 6

allauth配置上有一些适配器.例如这一个:

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

您可以通过覆盖默认适配器来指定新适配器.只需覆盖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
Run Code Online (Sandbox Code Playgroud)

然后修改settings.py上的ACCOUNT_ADAPTER

ACCOUNT_ADAPTER = '**app**.MyCoolAdapter'
Run Code Online (Sandbox Code Playgroud)

检查以下内容的默认行为:https: //github.com/pennersr/django-allauth/blob/master/allauth/account/adapter.py