检查Django中是否存在用户名 [英] Checking if username exists in Django

查看:574
本文介绍了检查Django中是否存在用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个Django项目,用户可以在一个表单中改变用户名和姓名。在forms.py中,我试图找出用户是否存在。如果是这样,它应该显示一个错误。问题是,如果用户想要改变他的姓氏,并将其用户名留在输入中,则会引发验证错误。显然,该用户名已经存在。有没有办法检查它是否等于当前登录的用户的用户名,并避免显示错误?

I am working on a Django project where users will be able to change their usernames along with their first and last name in one form. In forms.py, I am trying to find out if the user exists. If so, it should display an error. The problem is that if user wants to change his first and last name and leaves his username in the input, it raises a validation error. Obviously, that username already exists. Is there a way to check if it equals the username of currently logged user and avoid displaying the error?

class ChangeNameForm(forms.ModelForm):
    username = forms.CharField(max_length=30)
    first_name = forms.CharField(max_length=255)
    last_name = forms.CharField(max_length=255)

    def clean_username(self):
        username = self.cleaned_data['username']

        try:
            user = User.objects.get(username=username)
        except user.DoesNotExist:
            return username
        raise forms.ValidationError(u'Username "%s" is already in use.' % username)

谢谢。

推荐答案

当ModelForms被绑定对于一个模型对象,它们有一个名为instance的属性,它是模型对象本身。在您看来,当 request.method =='POST'时,您可能正在创建这样的表单实例:

When ModelForms are bound to a model object, they have an attribute called 'instance', which is the model object itself. In your view, when request.method == 'POST', you're probably creating the form instance like this:

form = ChangeNameForm(request.POST, instance=request.user)

如果是这样,您可以从表单方法访问记录的用户,验证方法可以是这样的:

If that's the case, you can access the logged user from the form methods, and your validation method can be something like this:

def clean_username(self):
    username = self.cleaned_data['username']
    try:
        user = User.objects.exclude(pk=self.instance.pk).get(username=username)
    except User.DoesNotExist:
        return username
    raise forms.ValidationError(u'Username "%s" is already in use.' % username)

考虑使用。exists 方法,因为它比您尝试检索更快的查询数据库所有使用 .get 方法的用户信息。而代码也有点清洁:

Consider using the .exists method, for it issues a faster query to your database than if you try to retrieve all the user information with the .get method. And the code gets a little cleaner too:

def clean_username(self):
    username = self.cleaned_data['username']
    if User.objects.exclude(pk=self.instance.pk).filter(username=username).exists():
        raise forms.ValidationError(u'Username "%s" is already in use.' % username)
    return username

提升ValidationError时这些准则

Optionally, you can also follow these guidelines when raising the ValidationError.

我现在无法测试此代码,所以如果有什么问题,请向我道歉。

I can't test this code right now, so I apologize if there's anything wrong.

这篇关于检查Django中是否存在用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆