Django自定义UsernameField表单验证不起作用

时间:2021-10-01 07:12:55

So I created a custom form field to validate for duplicate usernames. I'm using Django + Mongoengine as my database. I have that plugged and working with the django authentication system so I'm assuming it can be accessed from forms.py? Maybe that assumption is incorrect. So I have the field

所以我创建了一个自定义表单字段来验证重复的用户名。我正在使用Django + Mongoengine作为我的数据库。我已经插入并使用django身份验证系统,所以我假设它可以从forms.py访问?也许这个假设是不正确的。所以我有这个领域

class UsernameField(CharField):
    def to_python(self, value):
        if not value:
            return ""
        return value

    def validate(self, value):
        super(CharField, self).validate(value)

        try:
            # If the user object exists it won't throw an Error/Exception
            user=User.objects.get(username=value) 
            raise ValidationError("Username already exists")
        except:
            pass

But when I actually use it in my form, it always seems to validate correctly even though I've called checked if form.is_valid() is True

但是当我在我的表单中实际使用它时,即使我已调用checked,如果form.is_valid()为True,它似乎总是正确验证

2 个解决方案

#1


1  

You're raising exceptions in the try block but then snuffing them out in the except block with pass. Try this, it will check for the existing user and only fails if it exists.

你在try块中引发了异常,但随后在pass块中将它们扼杀了。试试这个,它将检查现有用户,只有在存在时才会失败。

    try:
        # If the user object doesn't exist, it validates
        user=User.objects.get(username=value) 
    except django.core.exceptions.DoesNotExist:
        pass
    else:
         #user does exist, barf.
        raise ValidationError("Username already exists")

#2


0  

Bah, it was a dumb mistake on my part. For some reason I forgot that the Error I was trying to raise would be caught by the try and I would get sent to the except route. Changing it to this works

呸,这对我来说是一个愚蠢的错误。由于某种原因,我忘记了我试图提出的错误将被尝试捕获,我将被发送到except路由。改变它的工作原理

class UsernameField(CharField):
    def to_python(self, value):
        if not value:
            return ""
        return value

    def validate(self, value):
        super(CharField, self).validate(value)
        usernameDuplicate = False

        try:
            # If the user object exists it won't throw an Error/Exception
            user=User.objects.get(username=value) 
            usernameDuplicate = True
        except:
            pass

        if usernameDuplicate==True:
            raise ValidationError("Username already exists")

#1


1  

You're raising exceptions in the try block but then snuffing them out in the except block with pass. Try this, it will check for the existing user and only fails if it exists.

你在try块中引发了异常,但随后在pass块中将它们扼杀了。试试这个,它将检查现有用户,只有在存在时才会失败。

    try:
        # If the user object doesn't exist, it validates
        user=User.objects.get(username=value) 
    except django.core.exceptions.DoesNotExist:
        pass
    else:
         #user does exist, barf.
        raise ValidationError("Username already exists")

#2


0  

Bah, it was a dumb mistake on my part. For some reason I forgot that the Error I was trying to raise would be caught by the try and I would get sent to the except route. Changing it to this works

呸,这对我来说是一个愚蠢的错误。由于某种原因,我忘记了我试图提出的错误将被尝试捕获,我将被发送到except路由。改变它的工作原理

class UsernameField(CharField):
    def to_python(self, value):
        if not value:
            return ""
        return value

    def validate(self, value):
        super(CharField, self).validate(value)
        usernameDuplicate = False

        try:
            # If the user object exists it won't throw an Error/Exception
            user=User.objects.get(username=value) 
            usernameDuplicate = True
        except:
            pass

        if usernameDuplicate==True:
            raise ValidationError("Username already exists")