Mario Mateaș
Mario Mateaș

Reputation: 1216

CSRF token missing or incorrect - Django

I'm trying to build a Django webapp to test the functionalities of a Forex Converter I installed with pip. I created an application with django-startapp Converter and routed the url /convert to the view convert_view().

This is my views.py file:

from django.shortcuts import render

from forex_python.converter import CurrencyRates

# Create your views here.

def convert_view(request):
    if request.method == "POST":
        c = CurrencyRates()
        print(c.convert('EUR', 'RON', request.POST.get('eur')))
    context = {}
    return render(request, "convert.html", context)

Also, because my view returns a template convert.html, I created a form there. This is my convert.html:

{% csrf_token %}

<form action="." method="POST">
    <input type="text" name="eur" placeholder="EUR">
    <input type="submit">
</form>

As you can see, just a simple page that has a form inside it, redirects to the same page and uses POST to send the data. It also uses the {% csrf_token %} tag, so there shouldn't be any problems.

When I navigate to /convert everything works fine. I type in the amount of money I like to convert from EUR to RON, but when I send the POST request, I get redirected to an error page, telling me:

CSRF token missing or incorrect.

I read another article on stack overflow about not using request as a parameter in the render() function, but I'm doing it.

What is wrong? What can I do to fix this error? Thank you.

Upvotes: 3

Views: 4993

Answers (4)

samkayz
samkayz

Reputation: 97

There is error in your form file, your csrf_token is expected to be inside your tag because django is expecting it with the form data as to certify that what you are sending is safe. Try this

   <form action="." method="POST">
          {% csrf_token %}
           <input type="text" name="eur" placeholder="EUR">
           <input type="submit">
     </form>

It will work that way.

Upvotes: 1

Rahul Palve
Rahul Palve

Reputation: 96

{% csrf_token %} should be inside the form tag. like this

<form action="." method="POST">
{% csrf_token %}
       <input type="text" name="eur" placeholder="EUR">
       <input type="submit">
</form>

The reason behind that is because {% csrf_token %} is rendered like this, and inorder input to be submitted along with form it needs to be inside form element.

<input type="hidden" name="csrfmiddlewaretoken" value="0gdrskkUXOTenFZOWxhzQPZWavohLKrEaOm0aKj8KzOfeLFah9PihEdYG24Fl4F7">```

Upvotes: 2

Shamir Imtiaz
Shamir Imtiaz

Reputation: 183

Please put {% csrf_token %} inside <form> tag. This will solve the issue.

Upvotes: 5

user15256253
user15256253

Reputation:

You need to put {% csrf_token %} inside the <form> tag like this:

<form action="." method="POST">
    {% csrf_token %}
    <input type="text" name="eur" placeholder="EUR">
    <input type="submit">
</form>

Upvotes: 1

Related Questions