1

I'm getting an error while updating database records in django 1.8

Forbidden (403)
CSRF verification failed. Request aborted.

my url:

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

news/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
  • do u have 'django.middleware.csrf.CsrfViewMiddleware' in your middlewares ?
    – levi
    Oct 13, 2015 at 4:51

1 Answer 1

1

You need to add the csrf middleware to your settings.py file:

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

also, change

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

to

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

OR

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

This is because you need to add a context to each request.

Similar answer here

1
  • Maybe the context isn't included properly... try changing return render_to_response('news/edit.html',{'blogs':blogs}) to return render(request, 'news/edit.html', {'blogs': blogs})
    – Hybrid
    Oct 13, 2015 at 4:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.