简体   繁体   中英

Django - Forbidden (CSRF token missing or incorrect.)

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM