CSRF cookie未设置django ...验证失败

编程入门 行业动态 更新时间:2024-10-24 04:42:59
本文介绍了CSRF cookie未设置django ...验证失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

AoA 我是新的Django,我试图从POST获取数据,但得到错误CSRF cookie未设置,我试图很多通过google找到解决方案google和stackoverflow,但失败

AoA I am new to Django, I am trying to get data from POST, but getting error CSRF cookie not set, I tried alot to find the solution on google and stackoverflow via google too, but failed

这里是代码

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文件

HTML File

<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.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'),

settings.py

settings.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.middlewaremon.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', )

推荐答案

我有同样的问题,并通过添加 ensure_csrf_cookie decorator 到您的视图:

I had the same problem, and resolved it by adding the ensure_csrf_cookie decorator to your view:

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

它会在浏览器cookie中设置csrftoken,并且可以像这样创建ajax

It will set csrftoken in browser cookie and you can make ajax like this

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); } });

更多推荐

CSRF cookie未设置django ...验证失败

本文发布于:2023-10-18 13:15:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504328.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:CSRF   cookie   django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!