Reputation: 41
Hi have created a custom user model and introduced new fields for registration say for ex: phone and created custom adapter to save the field to database, but at the time of validation. clean_username() is used to check username already exist or not i need to check phone no for that username. so checking both username and phone no at same time. how can i get the phone no inside clean_username function. the below is the clean_username function in django allauth adapter
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
Upvotes: 4
Views: 1383
Reputation: 2262
You can validate only that specific field in the clean_{fieldname} function. For your case, you have to override the clean function, as your validation mechanism spans across different fields.
Your clean function will look something like this:
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
Upvotes: 2