Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 覆盖表单';s clean方法自定义错误消息_Python_Django_Forms_Overriding - Fatal编程技术网

Python 覆盖表单';s clean方法自定义错误消息

Python 覆盖表单';s clean方法自定义错误消息,python,django,forms,overriding,Python,Django,Forms,Overriding,重写内置Django表单()的clean方法时遇到问题。此表单有两个字段:新密码1和新密码2 因此,在我的views.py中,我调用定制表单(MySetPasswordForm): 在my forms.py中:我想定义自己的clean方法来显示自定义的错误消息。下面是我如何编写MySetPasswordForm的: def reset_confirm(request, uidb64=None, token=None): return password_reset_confirm_dele

重写内置Django表单()的clean方法时遇到问题。此表单有两个字段:新密码1和新密码2

因此,在我的views.py中,我调用定制表单(
MySetPasswordForm
):

在my forms.py中:我想定义自己的clean方法来显示自定义的错误消息。下面是我如何编写MySetPasswordForm的:

def reset_confirm(request, uidb64=None, token=None):
    return password_reset_confirm_delegate(request,
        template_name='app/reset_confirm.html',
        set_password_form = MySetPasswordForm, uidb64=uidb64, 
        token=token, post_reset_redirect=reverse('main_page'))
from django.contrib.auth.forms import SetPasswordForm
class MySetPasswordForm(SetPasswordForm):
    error_messages = {  'password_mismatch': _("Missmatch!"),  }

    def clean(self):
        password1 = self.cleaned_data.get('new_password1', '')
        password2 = self.cleaned_data.get('new_password2', '')

        print password1  #prints user's entered value
        print password2  #prints nothing!!
        print self.data['new_password2']  #prints user's entered value

        if password1 == '':
            self._errors["new_password1"] = ErrorList([u"enter pass1!"])

        if password2 == '':
            self._errors["new_password2"] = ErrorList([u"enter pass2"])

        elif password1 != password2:
            raise forms.ValidationError(
                    self.error_messages['password_mismatch'],
                    code='password_mismatch',
                )
        return self.cleaned_data   
问题是,当用户输入错误的重复密码时,不会出现
“Missmatch”错误
,而是给出
“enter pass2”
!另外,
print password2
不会打印用户为password2输入的值

我在这个代码里做错了什么?!定制错误消息的最佳方式是什么


p、 在视图中使用原始的SetPasswordForm可以很好地工作。
SetPasswordForm
检查方法中的
new\u password1
new\u password2
是否匹配

当密码不匹配时,
self.cleaned\u data
中不包括
new\u password2
,因此您无法使用
clean
方法访问它

class MySetPasswordForm(SetPasswordForm):
    error_messages = {
        'password_mismatch': _("Missmatch!"),  
        'required': _("Please enter a password"),  # If you do not require the fieldname in the error message
    }

    def __init__(self, *args, **kwargs):
        super(MySetPasswordForm, self).__init__(*args, **kwargs)
        self.fields['new_password1'].error_messages['required'] = _("enter pass1!")
如果要覆盖密码不匹配的错误消息,则在
error\u messages
dict中设置它是正确的方法。然后,我将从表单中删除
clean
方法

如果每个字段需要不同的
required
错误消息,可以在
\uuuu init\uuu
方法中进行设置

class MySetPasswordForm(SetPasswordForm):
    error_messages = {
        'password_mismatch': _("Missmatch!"),  
        'required': _("Please enter a password"),  # If you do not require the fieldname in the error message
    }

    def __init__(self, *args, **kwargs):
        super(MySetPasswordForm, self).__init__(*args, **kwargs)
        self.fields['new_password1'].error_messages['required'] = _("enter pass1!")

当您调用表单的clean方法super method
def clean_new_password2(self)
all ready被调用,因此
self.clean_数据['new_password2']
为空,您需要覆盖表单中的clean_new_password2,查找源代码


谢谢您的回答,那么我如何设置
错误消息
dict?您已经在问题中设置了
错误消息
dict。我添加了一个示例。很棒的tnx。我想我还是一个使用表单的新手:)我还需要对我的字段进行最小长度验证,我可以使用错误消息进行验证(如果是,如何验证?)还是必须使用clean方法?最好使用Django方法,而不是检查表单中的长度。谢谢你的回答,如何覆盖
清除新密码2
并执行其他验证?其他字段验证如何?我是否需要为它们使用另一种干净的方法?仅当您想要自定义它们时。