0

我重定向到新页面失败并出现错误,

登录.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>

网址.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.

设置.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
4

1 回答 1

5

我认为这很清楚:

失败原因:未设置 CSRF cookie。

在模板中,每个针对内部 URL 的 POST 表单内都有一个 {% csrf_token %} 模板标签。

您需要在表单中包含一个CSRF令牌:

https://docs.djangoproject.com/en/dev/ref/contrib/csrf/

<form method="post" action=".">{% csrf_token %}
于 2012-08-04T18:19:03.287 回答