Django注册表单中不区分大小写的用户名

时间:2019-01-13 06:23:43

标签: python django django-models django-forms

这是我的注册表格,

class SignupForm(forms.ModelForm):

   class Meta:
       model = User
       fields = ['first_name', 'last_name','username', 'email', 'password']

    def clean_username(self):
        username = self.cleaned_data.get('username')
        email = self.cleaned_data.get('email')

        if username and User.objects.filter(username=username).exclude(email=email).count():
            raise forms.ValidationError('This username has already been taken!')
       return username

这很好地检查是否存在相同的用户名。但是,它不检查是否区分大小写。如果有用户名,例如'userone',那么它也接受带有'Userone'的用户名。虽然它没有破坏任何功能,但是看起来很不专业。

我的问题是如何在表格中检查不区分大小写的字符并引发错误?

2 个答案:

答案 0 :(得分:1)

您可以在此处使用__iexact

User.objects.filter(username__iexact=username).exclude(email=email).exists()  # instead of count, used exists() which does not make any DB query

答案 1 :(得分:1)

有时我遇到同样的问题。 Django认为用户名唯一,无论大小写不同。就像我输入John一样,它是一个唯一的用户名,如果我输入john,它是一个新的用户名。我需要考虑Johnjohn不在数据库中。就像facebook一样简单,大写和小写的用户名都是相同的,唯一的。

所以我只需更改注册代码即可实现这一点。

username = self.cleaned_data.get('username').lower()

此外,在我的登录代码中,我将用户名转换为小写。 因此,它始终将用户名保存在数据库中较低的位置,并使用小写的用户名登录。尽管用户尝试使用大写的用户名登录,但通过转换为小写将其保存到数据库中。