Django allauth覆盖了clean_username和clean_email函数

时间:2017-06-17 09:40:51

标签: python django django-allauth

您已创建了自定义用户模型并引入了新的注册字段,例如ex:phone和创建自定义适配器以将字段保存到数据库,但在验证时。 clean_username()用于检查用户名是否已存在我需要为该用户名检查电话号码。所以同时检查用户名和电话号码。我如何在clean_username函数内部获取手机。以下是django allauth adapter

中的clean_username函数
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

1 个答案:

答案 0 :(得分:0)

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

你的清洁功能看起来像这样:

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