输入密码过短时网页不会提示错误,程序报错

来源:13-4 修改密码

这位同学很懒

2020-05-15

老师您好,在修改密码时密码输入过短不会提示 ‘确保改变至少包含几位字符’,而是程序报错。

  • 输入密码过短时不会提示此界面:
    不会提示次界面
  • 而是程序报错:
    图片描述
class ChangePwdView(LoginRequiredMixin, View):
    login_url = "/login/"
    def post(self, request, *args, **kwargs):
        pwd_form = ChangePwdForm(request.POST)
        if pwd_form.is_valid():
            # pwd1 = request.POST.get("password1", "")
            # pwd2 = request.POST.get("password2", "")
            #
            # if pwd1 != pwd2:
            #     return JsonResponse({
            #         "status":"fail",
            #         "msg":"密码不一致"
            #     })
            pwd1 = request.POST.get("password1", "")
            user = request.user
            user.set_password(pwd1)
            user.save()
            # login(request, user) #是否退出登录

            return JsonResponse({
                "status":"success"
            })
        else:
            return JsonResponse(pwd_form.errors)

class UploadImageView(LoginRequiredMixin, View):
    login_url = "/login/"

    # def save_file(self, file):
    #     with open("C:/Users/Administrator/PycharmProjects/MxOnline/media/head_image/uploaded.jpg", "wb") as f:
    #         for chunk in file.chunks():
    #             f.write(chunk)

 
class ChangePwdForm(forms.Form):
    password1 = forms.CharField(required=True, min_length=5)
    password2 = forms.CharField(required=True, min_length=5)

    def clean(self):
        pwd1 = self.cleaned_data["password1"]
        pwd2 = self.cleaned_data["password2"]

        if pwd1 != pwd2:
            raise forms.ValidationError("密码不一致")

        return self.cleaned_data




class UserInfoForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ["nick_name", "gender", "birthday", "address"]

报错:

[15/May/2020 01:34:25] "GET /media/head_image/2020/05/ea75e684-9def-4176-bb6d-d270bf6e3828.jpeg HTTP/1.1" 304 0
Internal Server Error: /users/update/pwd/
Traceback (most recent call last):
  File "/Users/.virtualenvs/mxonline/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/.virtualenvs/mxonline/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/.virtualenvs/mxonline/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/.virtualenvs/mxonline/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/.virtualenvs/mxonline/lib/python3.7/site-packages/django/contrib/auth/mixins.py", line 52, in dispatch
    return super().dispatch(request, *args, **kwargs)
  File "/Users/.virtualenvs/mxonline/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/PycharmProjects/MxOnline/apps/users/views.py", line 22, in post
    if pwd_form.is_valid():
  File "/Users/.virtualenvs/mxonline/lib/python3.7/site-packages/django/forms/forms.py", line 185, in is_valid
    return self.is_bound and not self.errors
  File "/Users/.virtualenvs/mxonline/lib/python3.7/site-packages/django/forms/forms.py", line 180, in errors
    self.full_clean()
  File "/Users/.virtualenvs/mxonline/lib/python3.7/site-packages/django/forms/forms.py", line 382, in full_clean
    self._clean_form()
  File "/Users/.virtualenvs/mxonline/lib/python3.7/site-packages/django/forms/forms.py", line 409, in _clean_form
    cleaned_data = self.clean()
  File "/Users/PycharmProjects/MxOnline/apps/users/forms.py", line 27, in clean
    pwd1 = self.cleaned_data["password1"]
KeyError: 'password1'
[15/May/2020 01:34:36] "POST /users/update/pwd/ HTTP/1.1" 500 18813

userceter-info.html

{% extends 'usercenter-base.html' %}
{% block title %}个人信息- 慕学在线网{% endblock %}
{% block custom_bread %}
     <section>
        <div class="wp">
            <ul  class="crumbs">
                <li><a href="{% url 'index' %}">首页</a>></li>
                <li><a href="{% url 'users:info' %}">个人中心</a>></li>
                <li>个人信息</li>
            </ul>
        </div>
    </section>
{% endblock %}
{% block rigt_form %}
     <div class="right">
		<div class="personal_des ">
			<div class="head" style="border:1px solid #eaeaea;">
				<h1>个人信息</h1>
			</div>
			<div class="inforcon">
				<div class="left" style="width:242px;">
                    <iframe id='frameFile' name='frameFile' style='display: none;'></iframe>
                    <form class="clearfix" id="jsAvatarForm" enctype="multipart/form-data" autocomplete="off" method="post" action="{% url 'users:image' %}" target='frameFile'>
                        <label class="changearea" for="avatarUp">
                            <span id="avatardiv" class="pic">
                                <img width="100" height="100" class="js-img-show" id="avatarShow" src="{{ user.image.url }}"/>
                            </span>
                            <span class="fl upload-inp-box" style="margin-left:70px;">
                                <span class="button btn-green btn-w100" id="jsAvatarBtn">修改头像</span>
                                <input type="file" name="image" id="avatarUp" class="js-img-up"/>
                            </span>
                        </label>
                    {% csrf_token %}
                    </form>
                    <div style="border-top:1px solid #eaeaea;margin-top:30px;">
                        <a class="button btn-green btn-w100" id="jsUserResetPwd" style="margin:80px auto;width:100px;">修改密码</a>
                    </div>
				</div>
				<form class="perinform" id="jsEditUserForm" autocomplete="off">
					<ul class="right">
						<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;称:
                           <input type="text" name="nick_name" id="nick_name" value="{{ user.nick_name|default_if_none:''}}" maxlength="10">
                            <i class="error-tips"></i>
                        </li>
						<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;日:
                           <input type="text" id="birth_day" name="birthday" value="{{ user.birthday|default_if_none:''|date:'Y-m-d' }}" readonly="readonly"/>
                            <i class="error-tips"></i>
						</li>
						<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别:
							<label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio"  name="gender" value="male" {% if user.gender == 'male' %}checked="checked"{% endif %}>男</label>
							<label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" name="gender" value="female" {% if user.gender == 'female' %}checked="checked"{% endif %}>女</label>
						</li>
						<li class="p_infor_city">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;址:
                            <input type="text" name="address" id="address" placeholder="请输入你的地址" value="{{ user.address }}" maxlength="10">
						    <i class="error-tips"></i>
                        </li>
                        <li>&nbsp;&nbsp;&nbsp;&nbsp;号:
                            <input class="borderno" type="text" name="mobile" readonly="readonly" value="{{ user.mobile }}">
                            <span class="changeemai_btn green changephone-color">[修改]</span>
                        </li>
						<li class="button heibtn">
							<input type="button" id="jsEditUserBtn" value="保存">
						</li>
					</ul>
                {% csrf_token %}
				</form>
			</div>
		</div>
	</div>
{% endblock %}

deco-user.js

$(function(){
    //个人资料修改密码
    $('#jsUserResetPwd').on('click', function(){
        Dml.fun.showDialog('#jsResetDialog', '#jsResetPwdTips');
    });
    $('#jsResetPwdBtn').click(function(){
        $.ajax({
            cache: false,
            type: "POST",
            dataType:'json',
            url:"/users/update/pwd/",
            data:$('#jsResetPwdForm').serialize(),
            async: true,
            success: function(data) {
                if(data.password1){
                    Dml.fun.showValidateError($("#pwd"), data.password1);
                }else if(data.password2){
                    Dml.fun.showValidateError($("#repwd"), data.password2);
                }else if(data.__all__){
                    Dml.fun.showValidateError($("#repwd"), data.__all__);
                }else if(data.status == "success"){
                    Dml.fun.showTipsDialog({
                        title:'提交成功',
                        h2:'修改密码成功,请重新登录!',
                    });
                    Dml.fun.winReload();
                }else if(data.msg){
                    Dml.fun.showValidateError($("#pwd"), data.msg);
                    Dml.fun.showValidateError($("#repwd"), data.msg);
                }
            }
        });
    });
写回答

4回答

云渊阁主

2021-02-04

clean这个函数应该用data取值,用cleaned_data 是本末倒置,只有clean函数验证通过后才能返回cleaned_data
0
0

Hi_Mike

2020-08-12

  # 处理表达验证                                                              
~                              |   96     def clean(self):                                                            
~                              |   97         pwd1 = self.data["password1"]                                           
~                              |   98         pwd2 = self.data["password2"]                                           
~                              |   99                                                                                 
~                              |  100         if pwd1 != pwd2:                                                        
~                              |  101             raise forms.ValidationError("密码不一致")                           
~                              |  102         return self.data

//img1.sycdn.imooc.com/szimg/5f34071b09cc771c14250127.jpg

修改老师定义form的源码 把cleaned_data 换成 data 就可以了。我是通过此方法,修改了这个问题。希望能帮到你。因为我看了,pwd_form 没有cleaned_data 我的数据在data中。

0
0

Hi_Mike

2020-08-12

刚才回答问题的同学不对,我也遇到跟这个同学一样的问题,根本不是你们提到的前端页面input名字问题。奇怪的是这个问题,在我设置断点,跟踪的时候能够正常提示用户名密码过短,但是取消断点全速运行就报keyerror错误,此keyerror错误是进入了 

if pwd_form.is_valid():  

    pwd1 = request.POST.get("password1", "")   # 这个地方报错 

这段逻辑,按理 它不应该进入这段if逻辑,它应该进入else逻辑 因为form表达不符合定义最小要求。

//img1.sycdn.imooc.com/szimg/5f3402490946bff814330312.jpg

0
0

Ethreal

2020-05-15

KeyError: 'password1'  , 你要看看你是不是前端标签修改了input 标签中的name 值  //img1.sycdn.imooc.com/szimg/5ebdf746099caa9e18270678.jpg

0
1
bobby
正解。
2020-05-17
共1条回复

Django+ xadmin 开发在线教育网站

一套通用的技术组合拳,助你解决大部分Python类网站后端问题

1911 学习 · 2149 问题

查看课程