Search code examples
pythondjangodjango-viewsdjango-csrfcsrf-token

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.


Solution

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