首页 > 解决方案 > 如何解决 AttributeError:'NoneType' 对象在 Django 中没有属性 'encode'

问题描述

我尝试使用 JAVASCRIPT 对 HTML 文件中的给定表单进行验证,并使用 AJAX 检查数据库表中的电子邮件是否可用。还从 hashlib 导入了 sha256。但我收到了这样的错误。我不明白为什么会发生此错误。任何人都可以提出解决此问题的方法。

Internal Server Error: /User/Registration/
Traceback (most recent call last):
  File "C:\PYTHON\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\PYTHON\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\Project\salon\user\views.py", line 214, in userregister
    epassword = sha256(upassword.encode()).hexdigest()
AttributeError: 'NoneType' object has no attribute 'encode'

HTML 文件:

<!DOCTYPE html>
<html lang="en">
{% load static %}
<head>
    <meta charset="UTF-8">
    <title>User Registration</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link href="{% static 'styles/style.css' %}" rel="stylesheet"/>
    <script type="text/javascript" language="javascript">
        function getsid(str)
        {   print(str)
            if(window.XMLHttpRequest)
            {
                xmlhttp= new XMLHttpRequest();
            }
            xmlhttp.onreadystatechange=function()
            {
                 if(xmlhttp.readystate==4 &&  xmlhttp.status==200)
                 {
                    document.getElementById("lemail").innerHTML= xmlhttp.responseText;
                 }
           }
             xmlhttp.open("GET","{% url 'checkemail' %}?id="+str,true);
             xmlhttp.send(null);
        }
    </script>
</head>
<body>
   <section class="sreg" id="sreg">
        <div class="container-fluid">
            <div class="htop">
                <h4>User <span>Register Form</span></h4>
            </div>
            <div class="row">
                <div class="col-12">
                        <form method="POST" name="contact" action="{% url 'userregister' %}">
                             {%csrf_token%}
                            <div class="form-row">
                                <div class="form-group col-md-6">
                                    <label for="fname">First Name</label>
                                    <input type="text" class="form-control" id="fname" name="fname" placeholder="First Name">
                                    <span id="lfname"></span>
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="lname">Last Name</label>
                                    <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name">
                                    <span id="llname"></span>
                                </div>
                            </div>
                             <div class="form-group">
                                 <label for="email">Email</label>
                                 <input type="email" class="form-control" id="email" name="email" placeholder="Email" onchange="getsid(this.value)">
                                 <span id="lemail"></span>
                             </div>
                            <div class="form-group">
                                <label for="password">Password</label>
                                <input type="password" class="form-control" id="password" name="pass" placeholder="Password">
                                <span id="lpass"></span>
                            </div>
                            <div class="form-group">
                                <label for="cpassword">Confirm Password</label>
                                <input type="password" class="form-control" id="cpassword" name="cpass" placeholder="Confirm Password">
                                <span id="lcpass"></span>
                            </div>
                            <div class="form-group">
                                 <label for="mobile">Mobile</label>
                                 <input type="text" class="form-control" id="mobile" name="mobile" placeholder="Mobile">
                                 <span id="lmob"></span>
                             </div>
                             <div class="form-group">
                                 <label for="address">Address</label>
                                 <textarea class="form-control" id="address" name="address" rows="3" placeholder="Address"></textarea>
                                 <span id="laddress"></span>
                             </div>
                             <center>
                                 <button type="submit" class="btn btn-success" onclick="return userregister()">Submit</button>
                              </center>
                        </form>
                </div>
            </div>
        </div>
    </section>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="{% static 'js/scriptfunction.js' %}"></script>
</body>
</html>

视图.py

def userregister(request):
if request.method == 'POST':
    ufname = request.POST.get('fname')
    ulname = request.POST.get('lname')
    uemail = request.POST.get('email')
    upassword = request.POST.get('password')
    ucpassword=request.POST.get('cpassword')
    epassword = sha256(upassword.encode()).hexdigest()
    umobile = request.POST.get('mobile')
    uaddress = request.POST.get('address')

    if (clientreg.objects.filter(Email=uemail).exists()):
        messages.info(request, "Email ID Already Taken")
        return redirect('userregister')
    elif (upassword!=ucpassword):
        messages.info(request, "Password Doesn't Match")
        return redirect('userregister')
    elif (clientreg.objects.filter(Mobile=umobile).exists()):
        messages.info(request, "Mobile Number Already Taken")
        return redirect('userregister')

    else:
        cloginobj = clientlogin()
        cloginobj.Username = uemail
        cloginobj.Password = epassword
        cloginobj.save()

        cuserreg = clientreg()
        cuserreg.Login_id = cloginobj
        cuserreg.First_name = ufname
        cuserreg.Last_name = ulname
        cuserreg.Email = uemail
        cuserreg.Password = epassword
        cuserreg.Mobile = umobile
        cuserreg.Address = uaddress
        cuserreg.save()
        userdetails = clientlogin.objects.get(Username=uemail, Password=epassword)
        cid = userdetails.id
        request.session['cid'] = cid
        return redirect("userhome")

else:
    return render(request, "userregister.html")


def checkemail(request):
useremail = request.GET["id"]
count=clientlogin.objects.filter(Username=useremail).count()
if count==0:
    return HttpResponse("Email Id is available")
else:
    return HttpResponse("Email Id already exist")

网址.py

from django.urls import path,re_path
from . import views

urlpatterns=[
    path('User/Registration/', views.userregister, name="userregister"),
    path('User/Registration/CheckEmail', views.checkemail, name="checkemail"),    
    ]

标签: javascriptpythondjangoajaxsha256

解决方案


它的价值upassword似乎是无。

 upassword = request.POST.get('password')

似乎发布数据没有password. 您可以检查该值是否是从 POST 请求传递的。

一次处理的方法是:

try:
    upassword = request.POST['password']
except KeyError:
    // password value not passed in POST request
    // return HTTPResponse with 400 code

推荐阅读