Django ошибка доступа 403 ошибка проверки csrf запрос отклонен

When you have «Forbidden (403) CSRF verification failed. Request aborted» you can alternatively do:

option (2) (not preferred)

import:

from django.template.context_processors import csrf

add to context:

context = {}
context.update(csrf(request))

return:

-Django > 1.9 has «context» instead of «context_instance»

return render_to_response("login.html",
    {"registration_id":registration_id},
    context=context)

option (3) (preferred)

import:

-instead of importing «render_to_response» import «render»

from django.shortcuts import render

return:

return render(request, "login.html", context)

Apparently option 3 is preferable, because «render» is shorter than «render_to_response», especially if you need to import and add stuff. I could imagine option 2 keeps a leaner context dict, but this seems trivial (?).

For clarity:

Both solutions still need the {% csrf_token %} in your html form as mentioned above. And never turn off or comment the csrf middelware.

sources:

old Django 1.9 docs on RequestContext

Django 2 docs on the csrf processor

source explaining render is enough

Theory


A couple of things are required to make the csrf protection work (check out the docs):

  1. Your browser has to accept cookies from your server
  2. Make sure you have ‘django.middleware.csrf.CsrfViewMiddleware' included as middleware in your settings.py (alternatively use the decorator csrf_protect() on particular views you want to protect)
  3. Make sure you pass on the csrf token from django.core.context_processors.csrf to the context manager.

When you load your page, have a look in the page source using your favorite browser. Don’t open the template html file, open the url which point to the view containing the form. Look at where you placed the {% csrf_token %}. If you see something like

<input type='hidden' name='csrfmiddlewaretoken' value="jdwjwjefjwdjqwølksqøwkop2j3ofje" />

you should be ok.

If you on the other hand see NOTPROVIDED, something has gone wrong while creating the csrf token. By looking in the source code (context_processors.py and csrf.py), we can find out what:

  • csrf(request) returns {'csrf_token': 'NOTPROVIDED'} if get_token(request) returns None.
  • get_token(request) returns request.META.get("CSRF_COOKIE", None).

I assume this means that it would return None if the cookie isn’t successfully created.

Fix


For you, this means that you should first replace

<form action="/accounts/auth/" method="post" {% csrf_token %}>

with

<form action="/accounts/auth/" method="post">
{% csrf_token %}
(...)
</form>

We’d like the csrf field to be inside <form>...</form>, not inside <form>. As the code is at the moment, it will be converted to

<form action="/accounts/auth/" method="post" <input type='hidden' name='csrfmiddlewaretoken' value='randomchars' />>

and we would rather like

<form action="/accounts/auth/" method="post">
<input type='hidden' name='csrfmiddlewaretoken' value='randomchars' />

After that — have a look at the source code, and see if you can find the csrf field. If you can see it, everything should work in theory.

You can also check that the csrf cookie has been set in your browser, e.g. in Chrome, right-click the web page, and select Insepect Element. Select the Resources tab, and click on cookies. You should find a cookie name csrftoken there.

If you still have problems, double-check the middleware tuple in your settings.py and double-check that your browser accept cookier from your server as described above.

Cover image for Unable to Login Django Admin after Update : Giving Error Forbidden (403) CSRF verification failed. Request aborted.

Problem

Unable to Login Django Admin after Update : Giving Error Forbidden (403) CSRF verification failed. Request aborted.

This Issue Can happened suddenly after updating to Newer Version Of Django which looks like below image.

Forbidden (403) CSRF verification failed. Request aborted error image


Details

Django Project Foundation team made some changes in security requirements for all Django Version 4.0 and Above. In Which they made mandatory to create an list of urls getting any type of form upload or POST request in project settings named as CSRF_TRUSTED_ORIGINS.

They did not updated the details in latest tutorial documentation but they published the Changes Notes at https://docs.djangoproject.com/en/4.0/releases/4.0/#csrf-trusted-origins-changes-4-0.


First Solution

For localhost or 127.0.0.1.

Goto settings.py of your django project and create a new list of urls at last like given below

CSRF_TRUSTED_ORIGINS = ['http://*', 'https://*']

Enter fullscreen mode

Exit fullscreen mode

if Your running an project in localhost then you should open all urls here * symbol means all urls also there is http:// is mandatory.


Second Solution

This is Also for Localhost and for DEBUG=True.

Copy the list of ALLOWED_ORIGINS into CSRF_TRUSTED_ORIGINS like given below.

ALLOWED_ORIGINS = ['http://*', 'https://*']
CSRF_TRUSTED_ORIGINS = ALLOWED_ORIGINS.copy()

Enter fullscreen mode

Exit fullscreen mode


Third Solution

When Deploying you have to add urls to allow form uploading ( making any POST request ).

I Know this maybe tricky and time consuming but it’s now mandatory.

Also this is Mandatory to Online IDEs also like Replit, Glitch and Many More.


Conclusion

If you found this useful then please share this and follow me! Also check out Buy Me A Coffee if you want to support me on a new level!

Buy me a coffee

Give an reaction if any solutions helped you for algorithm boost to my content.

bye 👋.

1. Что такое csrf?

Проще говоря, его китайское название — «Подделка междоменных запросов. Вы можете видеть сложностьВот

2. Как использовать csrf в Django?

2.1 Типичные ошибки новичков

Если вы новичок в Django, вы, вероятно, столкнетесь с такой проблемой — когда внешний интерфейс использует почтовый запрос для передачи значения, необъяснимо возникает следующая ошибка …

1. Стрелка на рисунке выше является основной причиной ошибки: «Проверка CSRF не удалась, запрос был отклонен».
2. А содержимое синего поля — это несколько мест, на которые следует обратить внимание при использовании CSRF.

  • Браузеру необходимо включить файлы cookie
  • будут‘django.middleware.csrf.CsrfViewMiddleware’Добавьте его в MIDDLEWARE = ​​[xxx] в settings.py.
  • Чтобы{% csrf_token %}Поместите это в форму сообщения!
  • Для использования в фоновом режимеrender()метод!

2.2 Решение при возникновении ошибки 403
Блогер не внимательно ознакомился с мерами предосторожности при обнаружении этой ошибки. Но Baidu по привычке делал эту ошибку, читал кучу блогов, но так и не решил ее. Наконец, я внимательно прочитал меры предосторожности и обнаружил, что решение действительно в мерах предосторожности. (Ниже приведен способ обычного использования csrf. Если вы хотите быть простым, вы можете напрямую заблокировать csrf, но метод блокировки не рекомендуется.)
  2.2.1 Включите файлы cookie браузера

Сохраните возможность открытия файлов cookie в вашем браузере.

  2.2.2 Добавить конфигурацию

Конечно, этот параметр обычно настраивается автоматически при создании проекта.

  2.2.3 Добавьте {% csrf_token%} в форму публикации

  2.2.4 Функция фона использует метод render ()

Примечание. Упомянутая здесь функция — это не функция для обработки данных формы, а функция для перехода на страницу, где находится форма! ! !Блогер упал на последнем этапе, но, в конце концов, винит себя в своей глупости. Если вы сначала не дадите ему значение, как вы можете проверить это в фоновом режиме?

After implementing a new project with Django that should allow to me to send some long text to the server, then use the KeyBERT library to extract automatically the Keywords from the sent text and finally send me a JSON response with the result. Once I deployed the project to test it using Postman, I found this error when trying to send directly a POST request to my view in Django using Postman.

In this article, I will explain to you 2 possible ways to circumvent this exception when sending requests through Postman to your Django project.

A. Disable CSRF protection for as specific view

Disabling the CSRF protection of a real project or something that really requires it is in no one’s head. You shouldn’t definitively do this unless you know what you’re doing (you understand totally how a CSRF attack and how could it be a problem to your application if you allow form submission without CSRF protection). Some cases where it could be feasible to use this approach:

  • A local API that you’re testing locally only.
  • A public API that’s designed to be accessible for anyone but somehow you trust all the possible requests (e.g your API is only accessible for specific IPs like the IP of another server that requests information from this endpoint and it has already CSRF protection with another language like PHP).

Otherwise, don’t do it. In my case, I designed a basic API that runs a machine learning library and should return the result of it as response, however the API doesn’t need any user implementation as it’s mean to be used only for me. This approach consists of disabling the CSRF protection of a specific route:

# views.py
from django.http import JsonResponse

# 1. Import the csrf_exempt decorator
from django.views.decorators.csrf import csrf_exempt

# 2. Exempt the view from CSRF checks
@csrf_exempt
def extract_keywords(request):
    text = request.POST.get('text')
    return JsonResponse(text)

The decorator will disable the CSRF checks for the route, in this case the extract_keywords method of the view. If you send the POST request to the same route again with Postman, it should succeed this time.

B. Auto-set X-CSRFToken header in Postman

The second option will work only if you are facing the following situation. If you have a Django project working properly let’s say in the following URL http://localhost:8080/my-form and it answers to GET and POST requests. Your project works properly, when you access the Form address through the browser through a GET request, the form will be rendered so the user can easily submit the data and when it’s submitted through a POST request, the request succeeds in the browser as expected. The problem with Postman appears when it works in the browser, but if you try to simulate the POST request to the same address using Postman, the mentioned exception will appear.

As previously mentioned, Django has inbuilt CSRF protection. The only mechanism that you have to trigger an AJAX request when this protection is enabled is to add the X-CSRFToken header to your request (which should contain a valid CSRF token to validate in the server). You can obtain this token first triggering a GET request to the endpoint to obtain the token and then use a Postman test script to manipulate the subsequent request with JavaScript adding the required header.

To accomplish this, open the Tests tab of your postman request and add the following test code:

var xsrfCookie = postman.getResponseCookie("csrftoken");
postman.setEnvironmentVariable('csrftoken', xsrfCookie.value);

This test JavaScript is executed after the response is received. Once it’s there, run the GET request:

Postman GET request Django

What we did with the previous code is basically extracting the csrftoken of the form obtained with the GET request and it’s now going to be used in the subsequent POST request to validate the form. This token will be stored as an environment variable namely csrftoken, so we can easily add it to the new POST request as a new header:

Headers CSRF Token

After declaring the header, simply run the POST request and it should now succeed:

POSTMAN csrftoken Post

Happy coding ❤️!

  • Django rest framework обработка ошибок
  • Divinity original sin ошибка msvcp120 dll
  • Django is not importable in this environment ошибка
  • Divinity original sin ошибка msvcp110
  • Django admin ошибка проверки csrf запрос отклонен