sharataka
sharataka

Reputation: 5132

How to fix a CSRF verification error?

I am getting the error, "CSRF token missing or incorrect" though I believe I have included the right tag within the template. Below is the view and template that have been showing this error:

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            return HttpResponseRedirect('/contact/thanks/')
    else:
        form = ContactForm()
    return render_to_response('reserve/templates/contact_form.html',{'form': form})

Template:

<html>
<head>
    <title>Contact us</title>
</head>
<body>
    <h1>Contact us</h1>

    {% if form.errors %}
        <p style="color: red;">
            Please correct the error{{ form.errors|pluralize }} below.
        </p>
    {% endif %}

    <form action="" method="post">
    {% csrf_token %}
        <table>
            {{ form.as_p }}
        </table>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Upvotes: 1

Views: 447

Answers (2)

johndavidback
johndavidback

Reputation: 521

You should pass a context instance to your render_to_response

from django.template import RequestContext

return render_to_response('reserve/templates/contact_form.html', context_instance=RequestContext(request,{'form': form}))

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 600041

Notice item 3 of the instructions. A quick way to do this is to replace your render_to_response call with render(request, 'reserve/templates/contact_form.html',{'form': form}) (import it via from django.shortcuts import render).

Upvotes: 2

Related Questions