用户匹配查询不存在

时间:2015-09-20 12:40:04

标签: python django

class RegistrationForm(forms.Form):

     username = forms.CharField(label='Username', max_length=30)
     email = forms.EmailField(label='Email')
     password1 = forms.CharField(label='Password', widget=forms.PasswordInput(), max_length=15)

     password2 = forms.CharField(label='Password (again)', widget=forms.PasswordInput(), max_length=15)

     f_name = forms.CharField(label='First Name', max_length=20)
     l_name = forms.CharField(label='Last Name', max_length=10)
     m_no = forms.IntegerField(label='Mobile Number')
     country = forms.CharField(label='Country', max_length=20)
     state = forms.CharField(label='State', max_length=20)
     gender = forms.CharField(label='Sex', max_length=1)
     forte = forms.CharField(label='Quizzing Forte', max_length=20)


def clean_password2(self):
    if 'password1' in self.clean_data:
        password1 = self.clean_data['password1']
        password2 = self.clean_data['password2']

        if password1 == password2:
            return password2
    raise forms.ValidationError('Passwords do not match.')

def clean_username(self):
    uname = self.clean_data['username']
    if not re.search(r'^\W+$', username):
        raise forms.ValidationError('Username can only contain alphanumeric characters and underscore.')

    try:
        u = user.objects.get(username = uname)
    except ObjectDoesNotExist:
        return uname
    raise forms.ValidationError('Username not available')

以上代码会导致' ObjectDoesNotExist'例外。接下来是'用户匹配查询不存在'。我似乎无法识别错误。请帮助。

1 个答案:

答案 0 :(得分:1)

试试这个:

u = user.objects.filter(username=uname).first()
if not u:
    return uname
raise forms.ValidationError('Username not available')