2017-06-12 101 views
0

当我试图用在index.html的设置用户名和密码登录,出现错误如下:ValueError异常:(Django1.11.1 python3.6.1 pycharm)

ValueError at /login_action/ 
The view sign.views.login_action didn't return an HttpResponse object. It      returned None instead. 
Request Method: POST 
Request URL: http://127.0.0.1:8000/login_action/ 
Django Version: 1.11.1 
Exception Type: ValueError 
Exception Value:  
The view sign.views.login_action didn't return an HttpResponse object. It returned None instead. 
Exception Location: D:\python3.6.1\lib\site-  packages\django\core\handlers\base.py in _get_response, line 198 
Python Executable: D:\python3.6.1\python.exe 
Python Version: 3.6.1 
Python Path:  
['C:\\Users\\Administrator\\guest', 
'D:\\python3.6.1\\python36.zip', 
'D:\\python3.6.1\\DLLs', 
'D:\\python3.6.1\\lib', 
'D:\\python3.6.1', 
'D:\\python3.6.1\\lib\\site-packages'] 
Server time: Mon, 12 Jun 2017 08:29:35 +0000 

从暗示吗说,HttpResponse对象的valut是无

urls.py作为遵循

from django.conf.urls import url 
from django.contrib import admin 
from sign import views 
urlpatterns = [ 
url(r'^admin/', admin.site.urls), 
url(r'^index/$',views.index), 
url(r'^login_action/$',views.login_action), 
] 

views.py作为遵循

from django.shortcuts import render 
from django.http import HttpResponse 
# Create your views here. 
def index(request): 
return render(request,"index.html") 
# 登录函数定义 
def login_action(request): 
if request.method == 'post': 
    username = request.POST.get('username','') 
    password = request.POST.get('password','') 
    if username == 'admin'and password == 'admin123': 
     return HttpResponse('恭喜您,登录成功!') 
    else: 
     return render(request,'index.html',{'error':'用户名或者登录密码错误!'}) 

index.html作为跟随

<html> 
<head> 
    <title>欢迎登陆点米年会发布会系统</title> 
</head> 
<body> 
<h1>年会签名系统登陆<br> 
    WELCOM TO DIAN MI</h1> 
<form method="post" action="/login_action/"> 
<input name="username" type="text" placeholder="用户名"><br> 
<input name="password" type="password" placeholder="登录密码"><br> 
    <button id="btn" type="submit"> 登陆</button> 
{{error}}<br> 
</form> 
</body> 
</html> 

the screenshot of the traceback of the error

回答

0
  1. 更好 使用的方法名大写字母:

    如果request.method == 'POST':

  2. 好多 使用基于类的观点:

    class LoginAction(查看): def post(self,request):
    代码

+0

完全不同意第二点 - 基于类的视图有它们的用例,但它们现在比基于函数的视图更好(就像锤子不比螺丝刀“好”一样)。 –

+0

将http方法映射到适当的类方法,如果方法不允许,则引发405,这就是View所做的。这里没有看到基于类的视图的问题。 当我看到模式'if request.method =='XXXX'...我认为在基于类的视图中实现post方法更具可读性。 – KePe

+0

@KePe非常感谢,它确实来自案例问题 –

0

大写的request.method一样,

if request.method == 'POST': 
0

上线 “POST” 支票request.method == 'post'必须是大写的views.py文件。