Django-Allauth中的自定义表单验证 [英] Custom Form Validation in Django-Allauth

查看:95
本文介绍了Django-Allauth中的自定义表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对django-allauth中的字段进行一些额外的验证。例如,我想避免使用免费的电子邮件地址。所以我想在注册时运行此方法

I want to do some extra validation on fields in django-allauth. For example I want to prevent using free email addresses. So I want to run this method on signup

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."))

类似地,我想在电子邮件地址以外的其他字段上运行自定义验证。我该如何执行呢?

Similarly I want to run custom validation on different fields other than email address. How can I perform this?

推荐答案

allauth配置上有一些适配器。例如以下示例:

There are some adapters on the allauth configuration. For example this one:

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

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

You can specify a new adapter by overriding the default one. Just override the clean_email method.

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

然后在设置上修改ACCOUNT_ADAPTER。py

Then modify the ACCOUNT_ADAPTER on the settings.py

ACCOUNT_ADAPTER = '**app**.MyCoolAdapter'

在以下位置检查默认行为:
https://github.com/pennersr/django-allauth/blob/master/allauth/account/adapter.py

Check the default behavior on: https://github.com/pennersr/django-allauth/blob/master/allauth/account/adapter.py

这篇关于Django-Allauth中的自定义表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆