2017-06-17 27 views
2

您已经创建了一个自定义用户模型,并为ex:phone创建了注册新字段,并创建了自定义适配器以将字段保存到数据库,但是在验证时。 clean_username()用于检查用户名是否存在或不需要检查该用户名的电话号码。所以在同一时间检查用户名和电话号码。我怎么能在clean_username函数里面没有电话。以下是在Django allauth适配器clean_username功能Django allauth覆盖clean_username和clean_email函数

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 
+0

我怎样才能从clean_username函数的形式在手机细节来验证它与用户名一起 – karthi

回答

0

您可以在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