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

i am trying to do a login in django but i get this error, i check the CSRF documentation and nothing works for me. Here is the HTML:
<div c...

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.

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.

Pretty new to Django. Working through a second project following the Polls tutorial on Django website. Previous effort went well, albeit simple. This time around encountering problems accessing admin login.

I have created a superuser and using those credentials, when I try to login to http://127.0.0.1:8000/admin/login/?next=/admin/ I get the following error:

Forbidden (403)
CSRF verification failed. Request aborted.
Reason given for failure:
    CSRF cookie not set.

Looking at this and this, most answers either detail clearing browser cookies (did that), include 'django.middleware.csrf.CsrfViewMiddleware' in your middleware (which I do), or creating an exemption or workaround.

1) My question is why the admin portal does not seem to work now, but it did for my previous project and I am following the same steps?

2) Shouldn’t the properties for the admin panel be inherited through the project initiation?

3) How would I set the CSRF for admin when the documentation appears to state that the CSRF middleware is activated by default?

Thanks for any help.

settings.py

"""
Django settings for aptly project.

Generated by 'django-admin startproject' using Django 1.9.7.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os
import dj_database_url

from .secret_settings import *

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
PROJECT_DIR = os.path.join(PROJECT_ROOT,'../search')


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []



# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'search',
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'aptly.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'aptly.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        "ENGINE": "django.db.backends.postgresql_psycopg2",
        "NAME": "db_name",
        "USER": "me",
        "PASSWORD": "",
        "HOST": "localhost",
        "PORT": "",
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
    os.path.join(PROJECT_DIR, 'static'),
)

# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/

STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

#DATABASES['default'] = dj_database_url.config()

urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^admin/', admin.site.urls),
]

Directory

project
-aptly
--settings.py
--urls.py
--wsgi.py
-search
--templates
---index.html
--models.py
--urls.py
--views.py
manage.py

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

Shrikant Dhayje

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 👋.

При попытке входа в админку Django 4.* возникает 403-я ошибка CSRF Protection.

Согласно списку изменений CSRF_TRUSTED_ORIGINS changes в Django 4.*, вы должны добавить настройку CSRF_TRUSTED_ORIGINS в settings.py с явным указанием http протокола (‘http://’ иили ‘https://’)

Мои настройки выглядят следующим образом:

if DEBUG:
    CSRF_TRUSTED_ORIGINS = ['http://*', 'https://*']
if not DEBUG:
    CSRF_TRUSTED_ORIGINS = ['http://*.your-domain.ru', 'https://*.your-domain.ru'] # FIX admin CSRF token issue

Другие публикации из блога

Применяем разные сериализаторы для разных действий в Django Rest Framework GenericViewSet

Фактически нам нужно переопределить метод get_serializer_class() и с помощью условий добавить разные сериализаторы для …

Подробнее

Как запустить, перезапустить, остановить, узнать статус Nginx в Ubuntu?

Systemctl: startrestartstopstatus

sudo systemctl restart nginx
sudo systemctl start nginx
sudo systemctl sto…

Подробнее

JavaScript fetch с простой HTTP аутентификацией

Самый простой способ протестировать ваш API с базовой аутентификацией (логин, пароль).

Аналогичным образом работ…

Подробнее

Как создать virtualenv с разными версиями Python в Windows

Прежде всего у вас должны быть установлены разные версии Python в системе + virtualenv.

Ниже пример создания виртуал…

Подробнее

Разница между операторами «is» и «==» в Python

Оба оператора is и == предназначены для сравнения объектов в Python.

Оператор == сравнивает два значения.

Операто…

Подробнее

Как сгенерировать SECRET_KEY в Django?

Заходим в терминал:

python manage.py shell

Импортируем utils:

from django.core.management import utils

Гене…

Подробнее

Понравилась статья? Поделить с друзьями:
  • Django validation error code
  • Django validation error clean
  • Django send email error
  • Django save model error
  • Django return 500 error