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

时间:2014-04-25 23:15:56

标签: 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."))

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

1 个答案:

答案 0 :(得分:5)

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