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

时间:2013-09-12 18:46:52

标签: django validation mongoengine

所以我创建了一个自定义表单字段来验证重复的用户名。我正在使用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

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

2 个答案:

答案 0 :(得分:1)

你在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")

答案 1 :(得分:0)

巴哈,对我来说这是一个愚蠢的错误。由于某种原因,我忘记了我试图提出的错误将被尝试抓住,我会被发送到除路线。将其改为此作品

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")