CSRF验证失败。请求中止,Django发布请求

时间:2015-10-13 04:38:41

标签: python django

我在django 1.8中更新数据库记录时遇到错误

Forbidden (403)
CSRF verification failed. Request aborted.

我的网址:

url(r'^blog/update/(?P<id>[0-9]+)/$','news.views.update')

def edit(request,id):
    blogs = Blog.objects.get(pk=id)

    return render_to_response('news/edit.html',{'blogs':blogs})

def update(request,id):
    if request.method=='POST':
        blog = Blog.objects.get(pk=id)
        blog.title = request.POST.get('title')
        blog.content = request.POST.get('content')
        blog.save()
        return HttpResponse('updated successfully!!')
    else:
        return HttpResponse('error')

新闻/ edit.html

<form action="/blog/update/{{blogs.id}}/" method="POST">{%csrf_token%}
    <label>Title:</label>
    <input type="text" name="title" value="{{blogs.title}}"><br>
    <label>Content:</label>
    <textarea cols="45" rows="4" name="content">{{blogs.content}}</textarea><br>
    <input type="submit" value="submit">

</form>

1 个答案:

答案 0 :(得分:1)

您需要将csrf中间件添加到settings.py文件中:

MIDDLEWARE_CLASSES = (
...
'django.middleware.csrf.CsrfViewMiddleware',
)

另外,改变

return render_to_response('news/edit.html',{'blogs':blogs})

return render(request, 'news/edit.html', {'blogs': blogs})

OR

return render_to_response('news/edit.html', {'blogs': blogs}, context_instance=RequestContext(request))

这是因为您需要为每个请求添加上下文。

Similar answer here