2015-10-13 195 views
1

而在Django 1.8CSRF驗證失敗。請求中止,Django的POST請求

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> 
+0

做ü有 'django.middleware.csrf.CsrfViewMiddleware' 在你的中間件? – levi

回答

1

您需要添加csrf middl eware您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

+0

也許上下文沒有被正確包含......嘗試改變'return render_to_response('news/edit.html',{'blogs':blogs})''返回render(request,'news/edit.html', {'blogs':blogs})' – Hybrid

相關問題