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>
Kshitij Kulshrestha
  • 2,032
  • 1
  • 20
  • 27
Ranjeet Karki
  • 2,627
  • 4
  • 19
  • 30

1 Answers1

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

Community
  • 1
  • 1
Hybrid
  • 6,741
  • 3
  • 25
  • 45
  • 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 '15 at 04:59