为什么要检查Django中两个密码是否匹配如此复杂? [英] Why is checking if two passwords match in Django so complicated?

查看:106
本文介绍了为什么要检查Django中两个密码是否匹配如此复杂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做错事了,还是认真的这个 ?每次我想检查两个字段是否相同时,开发人员期望我写什么?

Am I doing something wrong, or is this seriously what the developers expect me to write every time I want to check if two fields are the same?

def clean(self):
    data = self.cleaned_data
    if "password1" in data and "password2" in data:
        if data["password1"] != data["password2"]:
            self._errors["password2"] = self.error_class(['Passwords do not match.'])
            del data['password2']    
    return data

为什么我必须验证用户名是唯一?

And why do I have to validate that the username is unique?

def clean_username(self):
    data = self.cleaned_data['username']
    if User.objects.filter(username=data).exists():
        raise ValidationError('Username already taken.')
    return data

这是一个 ModelForm 。它应该已经知道有一个独特的约束?

It's a ModelForm. It should already know there's a unique constraint?

推荐答案

这是我要做的:

这是您需要定义的唯一干净的方法,以确保2个密码正确,用户名有效。

This is the only clean method you need to define to make sure 2 passwords are correct and that the username is valid.

使用 clean_fieldname 方法,以便您不需要进行更多工作来验证用户名。

Use the clean_fieldname method so that you don't need to do more work to validate the username.

def clean_password2(self):
    password1 = self.cleaned_data.get('password1')
    password2 = self.cleaned_data.get('password2')

    if not password2:
        raise forms.ValidationError("You must confirm your password")
    if password1 != password2:
        raise forms.ValidationError("Your passwords do not match")
    return password2

你是绝对正确的,你不要需要验证用户名是唯一的,因为ModelForm知道它需要是唯一的。

You're absolutely right, you dont need to validate the username being unique, because the ModelForm knows it needs to be unique.

你的代码的问题是你覆盖了 clean()方法,这意味着ModelForm没有做到真正的'clean()。

The problem with your code is that you are overriding the clean() method, which means the ModelForm isn't doing its 'real' clean().

要获得默认验证,请调用 super(MyForm,self).clean()或更好,但不要覆盖 clean ,只能指定 clean_password2

To get the default validation, call super(MyForm, self).clean() or better yet don't override clean at all and only specify clean_password2.

这篇关于为什么要检查Django中两个密码是否匹配如此复杂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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