0

I am learning Django by creating a blog site. But when tried to use function based view to create a post got CSRF verification failed.

Using csrf_exempt decorator I could create post without error. But for security need to use CSRF protection, could anybody help with a solution please?

Django=1.11.5
Python=3.6.8

views.py

def post_create(request):
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            new_post = form.save(commit=False)
            new_post.author = request.user
            new_post.save()
            return HttpResponseRedirect('/')
    else:
        form = PostForm()
    return render_to_response('create.html',{ 'form': form })

create.html

<h2>Create your post here.</h2>
<form method="POST" enctype="multipart/form-data">
     {% csrf_token %}
     {{ form.as_p }}
     <input type="submit" value="CREATE">
</form>
markwalker_
  • 12,078
  • 7
  • 62
  • 99

3 Answers3

0

In your settings.py in MIDDLEWARE section add this:

'django.middleware.csrf.CsrfViewMiddleware',
Ramy M. Mousa
  • 5,727
  • 3
  • 34
  • 45
0

You shouldn't be using render_to_response. Use render which runs context processors such as the one that inserts the csrf token.

return render (request, 'create.html',{ 'form': form })
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

By replacing render_to_response with render clears this CSRF verification failed. But dont know how does it work? Anybody explain please what is going on?