4

AoA 我是 Django 的新手,我正在尝试从 POST 获取数据,但是没有设置错误的 CSRF cookie,我也尝试了很多在 google 和 stackoverflow 上通过 google 找到解决方案,但失败了

这是代码

视图.py

    from django.http import HttpResponse
    from django.template.loader import get_template
    from django.template import Context
    from django.template import RequestContext
    from django.core.context_processors import csrf
    from django.shortcuts import render_to_response

def search_Post(request):
    if request.method == 'POST':
            c = {}
        c.update(csrf(request))
        # ... view code here
                return render_to_response("search.html", c)

def search_Page(request):
    name='Awais you have visited my website :P'
    t = get_template('search.html')
    html = t.render(Context({'name':name}))
    return HttpResponse(html)

HTML 文件

<p>
          {{ name }}
            <form method="POST" action="/save/">
              {% csrf_token %}
              <textarea name="content" rows="20" cols="60">{{content}}</textarea><br>
              <input type="submit" value="Save Page"/>
            </form>
       <div>  Cant figure out any solution! :( </div>

 </p>

网址.py

 url(r'^home/$', 'contacts.views.home_Page'),
 url(r'^save/$', 'contacts.views.search_Post'),
 url(r'^edit/$', 'contacts.views.edit_Page'),
 url(r'^search/$', 'contacts.views.search_Page'),

设置.py

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.csrf',
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.request',
    'django.contrib.messages.context_processors.messages'
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
4

5 回答 5

8

我有同样的问题,并通过将ensure_csrf_cookie 装饰器添加到您的视图来解决它:

 from django.views.decorators.csrf import ensure_csrf_cookie
 @ensure_csrf_cookie
 def yourView(request):
     #...

它会在浏览器cookie中设置csrftoken,你可以像这样制作ajax

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
        }
    }
});
$.ajax({
        url: url,
        type: type,
        async: async,
        data: data,
        error: function (e) {},
        success: function (data) {
                returnFunction(data);
            }
    });
于 2014-05-21T15:23:46.827 回答
5

您使用这两种方法将 CSRF 令牌传递给模板处理器

c = {}
c.update(csrf(request))

RequestContext,虽然一个就足够了,请参阅 docs。但是你使用它错误的地方,服务'POST'请求。这些请求通常由您的浏览器在填写表单并希望获得结果时发送。

您的浏览器呈现 home.html 向服务器发送 GET 请求,该服务器由

t = get_template('home.html')
html = t.render(ResponseContext({'name':name}))
return HttpResponse(html)

你的代码的一部分。而且你使用任何手段来传递 csrf 令牌。因此,当您的模板处理器get_template().render()被调用时,它的上下文中没有标记,因此只需忽略模板中的 {% csrf_token %} 代码。因此,您必须RequestContext在 t.render(...) 视图的一部分中使用,或者将您的cdict 传递给那里。

您可以在浏览器窗口中检查生成的表单。

更新

seetings.py之后添加逗号'django.core.context_processors.csrf',现在的方式,它只是连接字符串。

应该:

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.csrf',
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
于 2013-10-25T20:43:23.927 回答
1

您似乎忘记传递渲染请求

Django 带有一个特殊的 Context 类,django.template.RequestContext,它的行为与普通的 django.template.Context 略有不同。第一个区别是它将 HttpRequest 作为其第一个参数。例如:

除了这些,RequestContext 总是使用 django.core.context_processors.csrf。这是管理员和其他 contrib 应用程序所需的与安全相关的上下文处理器,并且,在意外配置错误的情况下,它是故意硬编码的,并且不能通过 TEMPLATE_CONTEXT_PROCESSORS 设置关闭。

所以你需要的是

t = get_template('home.html')
c = RequestContext(request, {'name':name})
return HttpResponse(t.render(c))

如果你愿意,你可以在这里查看 django dock https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.RequestContext

于 2013-10-25T20:40:09.813 回答
1

从修复你的 HTML 开始(你忘了=):

<form method="POST" action="/search/save">
{% csrf_token %}
<textarea name="content" rows="20" cols="60">{{content}}</textarea><br>
<input type="submit" value="Save Page"/>
</form>

还:

def home_Page(request):
    #if request.method == 'GET':
    name='Awais you have visited my website :P'
    if request.method == 'POST':
        #name = request.POST.get('content')
        return render_to_response("search.html", {}, context_instance=RequestContext(request))

    return render_to_response("home.html", {'name':name}, context_instance=RequestContext(request))
于 2013-10-25T20:44:33.230 回答
-4

尝试使用带有端口号而不是 DNS 的确切 IP 地址......就像使用127.0.0.1和端口号代替localhost一样。

于 2015-01-19T20:27:23.207 回答