2

I have a problem with creating a simple form that uses {% csrf_token%}.

Template with form:

<form action="{% url 'library:my_view' %}" method="post">
   {% csrf_token %}
   <input type="submit" value="Submit">
</form>

urls.py

urlpatterns = [
        # ...
        path('some_page', views.my_view, name='my_view'),
]

views.py

def my_view(request):
        used_method = str(request.method)
        return render(request, 'library/some_template.html', {'test': used_method})

Template with result (some_template.html):

{{test}}

The server gives me the message:

Forbidden (CSRF token missing or incorrect.): / Library / some_page
"POST / library / some_page HTTP / 1.1" 403 2513

or (when i use a different browser):

Forbidden (CSRF cookie not set.): /library/some_page
"POST /library/some_page HTTP/1.1" 403 2868

The form works correctly when I disable protection by @csrf_exempt decorator . Where is a problem?

I will be grateful for any help.

Yugandhar Chaudhari
  • 3,831
  • 3
  • 24
  • 40
Marco
  • 81
  • 3
  • 7
  • Do you have ''django.middleware.csrf.CsrfViewMiddleware'' in your settings MIDDLEWARE list? – ipaleka Jul 16 '19 at 02:06
  • Yes, I do. This is the default setting. I didnt change it. – Marco Jul 16 '19 at 02:16
  • Do you have `CSRF_COOKIE_SECURE=True` in your `settings.py` and accessing your development server over http instead of https? – Scott Woodall Jul 16 '19 at 02:23
  • Dunno, your code is ok, it's probably some settings, cache, or similar – ipaleka Jul 16 '19 at 02:31
  • CSRF_COOKIE_SECURE = True/False - no diference SESSION_COOKIE_SECURE = True/False - no diference SECURE_SSL_REDIRECT = False - no diference, True - access HTTPS and I cant connet with localhost at all. – Marco Jul 16 '19 at 02:45
  • Possible duplicate: https://stackoverflow.com/questions/26639169/csrf-failed-csrf-token-missing-or-incorrect – jmunsch Sep 09 '19 at 20:03

1 Answers1

0

Here you are creating a empty form. what are you rendering inside the form? Did you create any forms.py file?

<form action="{% url 'library:my_view' %}" method="post">
   {% csrf_token %}
   <input type="submit" value="Submit">
</form>
Indiecoder
  • 186
  • 3
  • 17
  • 1
    I have not created any forms. py file. I'm working with the Django 2.2 tutorial and this file has not been introduced yet. I used a empty form because I wanted to explain my problem on the simplest example. Can it matter? When I add inputs that do something, the problem looks the same. The form works if I use @csrf_exempt and does not work with the token enabled. – Marco Jul 16 '19 at 22:59