Search code examples
djangocsrf-token

function based view failed on CSRF verification in Django 1.11.5


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>

Solution

  • 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 })