gpt4 book ai didi

python - CSRF验证失败。请求中止,Django Post 请求

转载 作者:太空宇宙 更新时间:2023-11-03 17:21:28 27 4
gpt4 key购买 nike

我在 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>

最佳答案

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

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

还有,改变

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

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

或者

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

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

Similar answer here

关于python - CSRF验证失败。请求中止,Django Post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33094243/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com