我重定向到新页面失败并显示错误
的login.html,
<html>
<head>
<title>Django Bookmarks -User Login</title>
</head>
<body>
<h1>User Login</h1>
{% if form.errors %}
<p>Your username and password didn't match</p>
{% endif %}
<form method="post" action=".">
<p><label for="id_username">Username:</label>
{{ form.username }}</p>
<p><label for="id_password">Password</label>
{{ form.password }}</p>
<input type="hidden" name="text" value="/" />
<input type="submit" value="login" />
</form>
</body>
</html>
urls.py
from django.conf.urls.defaults import patterns, include, url
from bookmarks.views import *
urlpatterns = patterns('',
(r'^$',main_page),
(r'^user/(\w+)/$',user_page),
(r'^login/$','django.contrib.auth.views.login'),
)
错误
Error:
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF cookie not set.
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:
•The view function uses RequestContext for the template, instead of Context.
•In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
•If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
settings.py文件
LOGIN_URL ='/login/'
LOGIN_REDIRECT_URL = '/login/'
新错误:
Page not found (404)
Request Method:
POST
Request URL:
http://127.0.0.1:8000/login/=%22.%22
Using the URLconf defined in django_bookmarks.urls, Django tried these URL patterns, in this order:
1. ^$
2. ^user/(\w+)/$
3. ^login/$
The current URL, login/=".", didn't match any of these
答案 0 :(得分:5)
我认为这很清楚:
失败原因:未设置CSRF cookie。
在模板中,每个POST表单中都有一个{%csrf_token%}模板标记,用于定位内部网址。
您需要在表单中添加CSRF
令牌:
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/
<form method="post" action=".">{% csrf_token %}