首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django allauth覆盖clean_username和clean_email函数

Django allauth覆盖clean_username和clean_email函数
EN

Stack Overflow用户
提问于 2017-06-17 17:40:51
回答 1查看 920关注 0票数 4

我创建了一个自定义用户模型,并引入了新的注册字段,例如:电话,并创建了自定义适配器以将字段保存到数据库中,但在验证时。clean_username()用于检查用户名是否已经存在,我需要检查用户名的电话号码。所以同时检查用户名和电话号码。我怎样才能让手机没有内部的clean_username功能。下面是django allauth适配器中的clean_username函数

代码语言:javascript
复制
def clean_username(self, username, shallow=False):
    """
    Validates the username. You can hook into this if you want to
    (dynamically) restrict what usernames can be chosen.
    """             

    if not USERNAME_REGEX.match(username):
        raise forms.ValidationError(_("Usernames can only contain "
                                      "letters, digits and @/./+/-/_."))

    # TODO: Add regexp support to USERNAME_BLACKLIST
    username_blacklist_lower = [ub.lower()
                                for ub in app_settings.USERNAME_BLACKLIST]
    if username.lower() in username_blacklist_lower:
        raise forms.ValidationError(_("Username can not be used. "
                                      "Please use other username."))
    # Skipping database lookups when shallow is True, needed for unique
    # username generation.
    if not shallow:
        username_field = app_settings.USER_MODEL_USERNAME_FIELD
        #appuuid_field = app_settings.USER_MODEL_APPID_FIELD
        assert username_field
        user_model = get_user_model()
        try:
            query = {username_field + '__iexact': username}                
            user_model.objects.get(**query)     
        except user_model.DoesNotExist:
            return username
        raise forms.ValidationError(
            _("This username is already taken. Please choose another."))
    return username
EN

回答 1

Stack Overflow用户

发布于 2017-06-25 11:42:01

您只能验证clean_{fieldname}函数中的特定字段。对于您的情况,您必须覆盖clean函数,因为您的验证机制跨越不同的字段。

您的clean函数将如下所示:

代码语言:javascript
复制
from allauth.account.forms import SignupForm as AllAuthSignupForm

class SignupForm(AllAuthSignupForm):
    def clean(self):
        super(SignupForm, self).clean()
        username = self.cleaned_data.get("username")
        phone = self.cleaned_data.get("phone")
        if not self._custom_username_phone_check(username, phone) and not self.errors:
            raise forms.ValidationError(_("Your username and phone do not match."))
        return self.cleaned_data
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44603047

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档