2015-01-21 130 views
2

我是django和web開發的新手。我試圖建立簡單的網站。我正在嘗試使用POST表單。但我正在採取「Forbidden 403,CSRF驗證失敗,請求中止」。我走過很多文章,但沒有任何反應。請告訴我我做錯了什麼。CSRF驗證失敗。請求中止。 Django 1.7

這是我的urls.py:

from django.conf.urls import patterns, include, url 
from django.contrib import admin 
from myapp import views 

urlpatterns = patterns('', 
    url(r'^admin/', include(admin.site.urls)), 
    url(r'^$', views.index, name = "index"), 
    url(r'^signup/', views.signup, name = "signup"), 
    url(r'^register/', views.register, name = "register"), 
) 

views.py

from django.shortcuts import render_to_response 
from django.http import HttpResponse 

def index(request): 
    return render_to_response("index.html") 

def signup(request): 
    return render_to_response("signup.html") 

def register(request): 
    return HttpResponse("It worked!") 

一個模板,我使用形式:signup.html

<html> 
<head> 
    <meta charset = "utf-8"> 
    <title> Регистрация </title> 
    <link rel = "stylesheet", type = "text/css", href = "{% static 'myapp/style.css' %}"> 
</head> 
<body> 
    <div class = "gradient"> 
     <table border = "0"> 
      <tr> 
       <td> <h1 class = "headerMargin"> MySite.com </h1> </td> 
       <td align = "right", width = "100%"> <button class = "btns"> Вход </button> </td> 
      </tr> 
     </table> 
    </div> 
    <form action = "/register/", method = "post"> 
    <table id = "registerArea", align = "center", border = "0", cellpadding = "10"> 
     <tr> 
      <td> <h2> Регистрация </h2> </td> 
     </tr> 
     <tr> 
      <td> 
       <div> <b> Имя пользователя: </b></div> 
       <input type = "text", size = "40"> </td> 
     </tr> 
     <tr> 
      <td> 
       <div> <b> Электронная почта: </b> </div> 
       <input type = "text", size = "40"> </td> 
     </tr> 
     <tr> 
      <td> 
       <div> <b> Пароль: </b> </div> 
       <input type = "password", size = "40"> </td> 
     </tr> 
     <tr> 
      <td> 
       <button id = "btnRegister", type = "submit"> <b> register </b> </button> </td> 
     </tr> 
    </table> 
    </form> 
    <div id = "footer"> 
     <table align = "center"> 
      <tr> 
       <td> <h4> О нас </h4> </td> 
       <td> <h4 class = "line"> Помощь </h4> </td> 
       <td> <h4 class = "line"> Правила </h4> </td> 
     </table> 
    </div> 
</body> 
</html> 

回答

4

裏面添加{% csrf_token %}模板標籤<form>標籤:

<form action = "/register/" method = "post"> 
    {% csrf_token %} 
    ... 
</form> 

文檔是here

另外您應該提供RequestContextrender_to_response。或者使用render()

from django.shortcuts import render 

def signup(request): 
    return render(request, "signup.html") 
+0

我已經嘗試添加{%csrf_token%}它不會幫助.... – 2015-01-21 11:57:08

+1

你不當使用'render_to_response'快捷。切換到'render()'。 – catavaran 2015-01-21 12:04:33

+0

@OlegKlimenko如果它解決了您的問題,您應該將此答案標記爲已接受。 :) – Bonifacio2 2015-01-21 12:32:55

相關問題