Search code examples
pythondjangotemplatescsrf

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>

Solution

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