我是django和web开发的新手。我正在尝试建立简单的网站。我正在尝试使用POST表单。但我正在采取“禁止403,CSRF验证失败。请求中止”。我走了很多文章,但没有任何反应。请告诉我,我做错了什么。
这是我的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>
答案 0 :(得分:4)
在{% csrf_token %}
标记内添加<form>
模板标记:
<form action = "/register/" method = "post">
{% csrf_token %}
...
</form>
文档为here。
另外,您应该向RequestContext
提供render_to_response
。或者使用render()
:
from django.shortcuts import render
def signup(request):
return render(request, "signup.html")