django csrf tokenhtml网页内有 {% csrf_token %} {{uf.as_p}}这样模板,怎么替换

5240人阅读
&html lang=&en&&
&title&Contact us&/title& &/head&
&h1&Contact us&/h1&
&form action=&.& method=&POST&&
&table& {{ form.as_table }} &/table&
&p&&input type=&submit& value=&Submit&&&/p&
以上我的测试template,form是一个forms对象,访问对应的URL的时候可以正常显示预定的页面,但是当点击提交按钮的时候就会出现&CSRF token missing or incorrect.&报错,报错页面中也提供了处理办法,基本就是& requestContext 用 Context()代替,然后在template中的post形式form中加入{% csrf_token %}。
按照其中的说法作了,对应template如下:
&html lang=&en&&
&title&Contact us&/title& &/head&
&h1&Contact us&/h1&
&form action=&.& method=&POST&&
{% csrf_token %}
&table& {{ form.as_table }} &/table&
&p&&input type=&submit& value=&Submit&&&/p&
但是没有效果,后来发现还需要在setting.py中加入对应的&MIDDLEWARE_CLASSES&。
对应加入:
'django.middleware.csrf.CsrfResponseMiddleware',
然后运行,OK。
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:104560次
积分:1191
积分:1191
排名:第16906名
原创:28篇
评论:15条
(1)(1)(2)(2)(1)(2)(1)(1)(1)(2)(4)(4)(4)(1)(2)(1)(1)(5)Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
In my users page, i have in place editing with ajax. And when i click edit, it works fine. But when i submit the form, it don't do anything. When i checked, this is the error:
CSRF verification failed. Request aborted.
So, how do I place {% csrf_token %} in my javascript? Please advice.
Thank you.
function bookmark_edit() {
var item = $(this).parent();
var url = item.find(".title").attr("href");
item.load("/save/?ajax&url=" + escape(url), null, function () {
$("#save-form").submit(bookmark_save);
$(document).ready(function () {
$("ul.bookmarks .edit").click(bookmark_edit);
function bookmark_save() {
var item = $(this).parent();
var data = {
url: item.find("#id_url").val(),
title: item.find("#id_title").val(),
tags: item.find("#id_tags").val()
$.post("/save/?ajax", data, function (result) {
if (result != "failure") {
item.before($("li", result).get(0));
item.remove();
$("ul.bookmarks .edit").click(bookmark_edit);
alert("Failed to validate bookmark before saving.");
save_form.html:
&form id = "save-form" method="post" action="/save/"&
{% csrf_token %}
{{form.as_p}}
&input type="submit" value="Save" /&
user_page.html:
{% extends "base.html" %}
{% block external %}
&script type = "text/javascript" src="{% static "assets/js/bookmark_edit.js" %}"&&/script&
{% endblock %}
{% block title %} {{username}} {% endblock %}
{% block head %} Bookmarks for {{username}} {% endblock %}
{% block content %}
{% include "bookmark_list.html" %}
{% endblock %}
@login_required(login_url='/login/')
def bookmark_save_page(request):
ajax = request.GET.has_key('ajax')
if request.method == 'POST':
form = BookmarkSaveForm(request.POST)
if form.is_valid():
bookmark = _bookmark_save(request, form)
variables = RequestContext(request, {
'bookmarks':[bookmark],
'show_edit':True,
'show_tags':True
return render_to_response('bookmark_list.html', variables)
return HttpResponseRedirect('/user/%s/' % request.user.username
return HttpResponseRedirect('failure')
elif request.GET.has_key('url'):
url = request.GET['url']
title = ''
link = Link.objects.get(url=url)
bookmark = Bookmark.objects.get(
link=link,
user = request.user
title = bookmark.title
tags = ' '.join(
tag.name for tag in bookmark.tag_set.all()
except ObjectDoesNotExist:
form = BookmarkSaveForm({
'url':url,
'title':title,
'tags':tags
form = BookmarkSaveForm()
variables = RequestContext(request, {
'form': form
return render_to_response(
'bookmark_save_form.html',
return render_to_response('bookmark_save.html',variables)
You are not sending the server generated csrf_token for the POST to verify the validity of the data. Hence the error.
As a part of the data part of the request, you need to send the token
csrfmiddlewaretoken: '{{ csrf_token }}'
Something like this
var data = {
url: item.find("#id_url").val(),
title: item.find("#id_title").val(),
tags: item.find("#id_tags").val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
Or you could simply do:
var data = $('form').serialize()
if you want to send the whole form as a dictionary
This is what I use. Not sure if it's applicable in your situation though.
// sending a csrftoken with every ajax request
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", $.cookie('csrftoken'));
3,62951534
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Stack Exchange
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
Stack Overflow works best with JavaScript enabled}

我要回帖

更多关于 csrf token 是什么 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信