-3

Hello I am trying to handle simple form submission in django. But still after hours of try. I am getting csrf verification failed error. I searched a lot but no solution is found so far.

This is my code

def index(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        useremail = request.POST.get('useremail')
    context = {
        'username': username,
        'useremail': useremail
    }

    template = loader.get_template('responsepage.html')
    return HttpResponse(template.render(context, request))
else:
    template = loader.get_template('formpage.html')
    return HttpResponse(template.render())

It is my form

<form method="post" action="/getdata/">
    {{% csrf_token %}}
    <input type="text" name="username" />
    <input type="email" name="useremail" />
</form>

I have written csrf_token variable here. But still I am getting the same error that csrf verification failed.

Reyaan Roy
  • 27
  • 4
  • 1
    you are probably missing {% csrf_token %} in your template (which you have not posted) – e4c5 Jul 11 '16 at 14:16
  • 1
    Possible duplicate of [Forbidden (403) CSRF verification failed. Request aborted. Even using the {% csrf\_token %}](http://stackoverflow.com/questions/20895526/forbidden-403-csrf-verification-failed-request-aborted-even-using-the-csr) – Two-Bit Alchemist Jul 11 '16 at 14:16
  • 1
    You tried and searched for _hours_? I find that difficult to believe. There are lots and lots of results for how to make CSRF verification work in Django. Marking your question as possible duplicate of one of them until you give us more information on where yours is failing. – Two-Bit Alchemist Jul 11 '16 at 14:16

2 Answers2

2

If you use the csrf token on the formpage.html template, then you need to render the template with the request object.

template = loader.get_template('formpage.html')
return HttpResponse(template.render(request=request))

You might want to simplify the code by using the render shortcut instead:

from django.shortcuts import render

def index(request):
    if request.method == 'POST':
        ...
        return render(request, 'responsepage.html', context)
    else:
        return render(request, 'formpage.html')
Alasdair
  • 298,606
  • 55
  • 578
  • 516
0

You should put this after your form tag in your view

{% csrf_token %}

And while rendering the output use

return render(request, 'responsepage.html', context)

Django gives this security feature to prevent cross site request forgery. If you don't want to use this feature of security you can temporarily disable it by putting

@csrf_exempt

Source: Django Forms Tutorial

Amrah Anam
  • 58
  • 1
  • 6