gpt4 book ai didi

python - Django allauth 覆盖 clean_username 和 clean_email 函数

转载 作者:行者123 更新时间:2023-12-04 13:03:44 26 4
gpt4 key购买 nike

您好已经创建了一个自定义用户模型并引入了新的注册字段,例如:电话并创建了自定义适配器以将该字段保存到数据库,但在验证时。 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com