2
votes

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.

1
Do you have ''django.middleware.csrf.CsrfViewMiddleware'' in your settings MIDDLEWARE list?ipaleka
Yes, I do. This is the default setting. I didnt change it.Marco
Do you have CSRF_COOKIE_SECURE=True in your settings.py and accessing your development server over http instead of https?Scott Woodall
Dunno, your code is ok, it's probably some settings, cache, or similaripaleka
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

1 Answers

0
votes

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>