python - Django allauth 覆盖 clean_username 和 clean_email 函数

标签 python django django-allauth

您好已经创建了一个自定义用户模型并引入了新的注册字段,例如:电话并创建了自定义适配器以将该字段保存到数据库,但在验证时。 clean_username() 用于检查用户名是否已存在我需要检查该用户名的电话号码。所以同时检查用户名和电话号码。我怎样才能在 clean_username 函数中获取电话号码。下面是 django allauth 适配器中的 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

最佳答案

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

您的 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

关于python - Django allauth 覆盖 clean_username 和 clean_email 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44603047/

相关文章:

python - 有没有办法删除 python 中的命令提示符 shell?

python - 使用 docker 容器设置开发环境时如何管理开发任务?

python - 如何序列化同一模型的外键

Django,根据用户类型将用户重定向到不同页面

django - 如何使用 django-allauth 将多个社交身份验证提供商连接到同一个 django 用户?

python - 我需要使用 apache 或 nginx 来托管服务器吗?

python - 使用 Hadoop Streaming 和 Python 读取/写入包含 Thrift 记录的序列文件

python - 在列表中附加不同的字典值

python - 呈现: 'utf8' codec can't decode byte 0xd0 in position 0: unexpected end of data时捕获到UnicodeDecodeError

django - 覆盖 Django allauth 注册 "next"重定向 URL