2017-06-12 97 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文件。