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

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

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

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.

Содержание

  1. Unable to Login Django Admin after Update : Giving Error Forbidden (403) CSRF verification failed. Request aborted.
  2. Problem
  3. Details
  4. First Solution
  5. Second Solution
  6. Third Solution
  7. Conclusion
  8. Top comments (0)
  9. Update Your DEV Experience Level:
  10. How to resolve Forbidden(403) if Django CSRF mechanism has not been used in POST method
  11. Cross Site Request Forgery protection
  12. 1. FORM
  13. 2. IN AJAX
  14. Issues
  15. Context Navigation
  16. #28488 closed Bug (fixed)
  17. Django 1.11+ raises CSRF verification failed if settings.DEBUG is False and an intermediate 404 page is requested
  18. Description (last modified by Ruben Alves )
  19. Attachments (3)
  20. Change History (44)
  21. Changed 5 years ago by Ruben Alves
  22. comment:1 Changed 5 years ago by Ruben Alves
  23. comment:2 Changed 5 years ago by Tim Graham
  24. comment:3 Changed 5 years ago by Ruben Alves
  25. comment:4 Changed 5 years ago by Tim Graham
  26. comment:5 Changed 5 years ago by Ruben Alves
  27. comment:6 Changed 5 years ago by Tim Graham
  28. comment:7 Changed 5 years ago by Ruben Alves
  29. comment:8 Changed 5 years ago by Tim Graham
  30. comment:9 Changed 5 years ago by Ruben Alves
  31. comment:10 Changed 5 years ago by Ruben Alves
  32. comment:11 Changed 5 years ago by Ruben Alves
  33. comment:12 Changed 5 years ago by Ruben Alves
  34. CSRF error on all POST requests #1912
  35. Comments
  36. Expected behaviour
  37. Actual behaviour
  38. Server configuration

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.

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

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

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.

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!

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

For further actions, you may consider blocking this person and/or reporting abuse

Update Your DEV Experience Level:

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠

Источник

How to resolve Forbidden(403) if Django CSRF mechanism has not been used in POST method

Are you a newbie to Django like me. ?

if yes , you would have come across “Forbidden (403)” when you are using forms or when you have used ajax post method to your app view and have not used CSRF mechanism properly. Below are ways I have resolved the 403 issues. Even before we see how CSRF should be used, we will see what CSRF is actually for.

Cross Site Request Forgery protection

“ The CSRF middleware and template tag provides easy-to-use protection against Cross Site Request Forgeries. This type of attack occurs when a malicious website contains a link, a form button or some JavaScript that is intended to perform some action on your website, using the credentials of a logged-in user who visits the malicious site in their browser. A related type of attack, ‘login CSRF’, where an attacking site tricks a user’s browser into logging into a site with someone else’s credentials, is also covered.”

CSRF middleware is enabled by default in your project settings.py file like below

Alternatively, If this is not enabled or set, you can still use the protection by decorating your views with csrf_protect

Ok now we have csrf protection on our views. Let us see how we can use it.

Using the csrf middleware token. Csrf middle ware token looks something like this below

1. FORM

We have to use the csrf_token tag inside the element if the form .for internal url

2. IN AJAX

First, we need to get the crsf cookie and this depends on whether CSRF_USE_SESSIONS and CSRF_COOKIE_HTTPONLY.

i) If CSRF_USE_SESSIONS and CSRF_COOKIE_HTTPONLY are False. You can get the cookie by using below function as in django documentation

Now the cookie is stored in csrftoken variable which can be used later in your ajax post.

Alternatively, you can also use the CND javascript library

You can then use the library method Cookies.get() to get cookie.

ii) If CSRF_USE_SESSIONS and CSRF_COOKIE_HTTPONLY are True
You can simply use jquery to get the cookie value like below

Secondly that we have the csrftoken available, we can simply specify in our ajax post method. In my example, I have used the jquery post method.

Now when you post to server URL, Django will process the request and there should be no 403 error.

Источник

Issues

Context Navigation

#28488 closed Bug (fixed)

Django 1.11+ raises CSRF verification failed if settings.DEBUG is False and an intermediate 404 page is requested

Reported by: Ruben Alves Owned by: nobody
Component: CSRF Version: dev
Severity: Release blocker Keywords: csrf failed settings debug false production
Cc: rubenanapu@…, Nicola, Jay Cox, Florian Apolloner, Berker Peksag Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Ruben Alves )

I’m using Django1.11 (and made tests also with Django1.11.4) and having problems when submitting a form with POST method.

I’m calling the <% csrf_token %>inside of the form, so, this is not the problem.
The problem when submitting the form is:

Forbidden (403)
CSRF verification failed. Request aborted.
More information is available with DEBUG=True.

Then, in order to see «more information», I’ve enabled settings.DEBUG to True and submitted the form again. At this moment, the problem didn’t happens anymore.

So I’ve disabled settings.DEBUG , submitted again, and the problem was there. Enabled DEBUG=True again, problem has gone.

Initially I thought that could be some error in my code, but the same happens when I try to reset my password wit the django.contrib.auth.views.password_reset view.

In my settings.py , I have the following changes that were made recently:

SECURE_PROXY_SSL_HEADER = (‘HTTP_X_FORWARDED_PROTO’, ‘https’)
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

I use AWS (Amazon Web Service) Elastic Beanstalk with https enabled.

The worst part is that I’ve discovered this only on production because I make all tests in my local machine with DEBUG=True , and on production, we set DEBUG=False . Also, the error message should be shown only if DEBUG=True .

Attachments (3)

Download all attachments as: .zip

Change History (44)

Changed 5 years ago by Ruben Alves

Error message on production with settings.DEBUG=False

Did you experience a change in Django 1.11 compared to Django 1.10 or earlier? I think you’ll need to debug the problem further and let us know why Django is at fault.

Before Django 1.11, I was using Django 1.8 and everything was working perfectly.

In order to use Django 1.11, I did all the changes mentioned on ​ https://docs.djangoproject.com/en/1.11/releases/1.11/

What I’ve done now was add settings.CSRF_FAILURE_VIEW = ‘courses.views.csrf_failure’ with DEBUG=False

I made my courses.views.csrf_failure raise an exception, so we could see the traceback.

The error message is:

The traceback is the following:

The traceback doesn’t give me any ideas about the cause. I think you’ll need to add further logging in django/middleware/csrf.py to find the root cause.

A large CSRF change between Django 1.8 and 1.11 is 5112e65ef2df1dbb95ff83026b6a962fb2688661. Perhaps you can test with Django 1.9 and 1.10 to help narrow the problem.

In the backwards-incompatible changes section of the 1.10 release notes, there’s a note, «CSRF token values are now required to be strings of 64 alphanumerics; values of 32 alphanumerics, as set by older versions of Django by default, are automatically replaced by strings of 64 characters. Other values are considered invalid. This should only affect developers or users who replace these tokens.» Maybe it’s relevant to you.

Ok, I’ve added some logs on django.middleware.csrf , and this is what I have:

Between lines 208 and 209 ( ​ https://github.com/django/django/blob/stable/1.11.x/django/middleware/csrf.py#L208) I’ve added a log and the value of csrf_token is vcdodHkRb8jlxQP5fnTjuQp5i3PMWYYEBOYfpOFkCEjWWwHMpJ9uqaPGI6vGi6hS

The value of request_csrf_token on line 311 ( ​ https://github.com/django/django/blob/stable/1.11.x/django/middleware/csrf.py#L311) before we call request_csrf_token = _sanitize_token(request_csrf_token) is tMgl4aTrdjOEShUax3Gz1CJLbvnhBWiEVzmzgTxSclDuP01lBfwoE2R6dDyljaCQ

After _sanitize_token be called, the value of request_csrf_token is the same, and the value of csrf_token is vcdodHkRb8jlxQP5fnTjuQp5i3PMWYYEBOYfpOFkCEjWWwHMpJ9uqaPGI6vGi6hS .

Maybe you can try to minimize the middleware, etc. in your project and see if something like that is causing the issue.

I’ve being testing to reload the page and see the Cookie named csrftoken .

On the system that runs with Django1.8 , every time I reload the page, the csrftoken Cookie has the same value.

On the system that runs with Django1.11 , every time I reload the page, the csrftoken Cookie has a different value.

Do you know if on Django1.11 is expected to have a different csrftoken Cookie every time I reload the page? If yes, why is expected to be different in Django1.11 and not in Django1.8 ?

But even if they are different, the function _unsalt_cipher_token ( ​ https://github.com/django/django/blob/stable/1.11.x/django/middleware/csrf.py#L62) should return always the same value with the different values on the Cookie, right?

I’ve called the _unsalt_cipher_token function with the different values of the Cookie, and the returned values are ALWAYS different.

I’ve created a template tag named uncypher that calls _unsalt_cipher_token as you can see below:

Then, on a html template I’ve added

After set settings.DEBUG=True and reload the page 3 times, on the JavaScript Console was printed the same value lKnMEqisHw8mxMIXZgZTKt9cirypfv1f on the 3 times that I’ve reloaded the page.

Then I’ve set settings.DEBUG=False and reloaded the page 4 times again.
On the first time it printed the same value lKnMEqisHw8mxMIXZgZTKt9cirypfv1f . On the second YgnNvwBJJwAID17nl7FLhtA3rObtvGLX , third time printed hB1plGV688FpDPNu9waO1H959c04YLPM and fourth time printed C2sJ9e7coe74juO6HxAY4RIppBY4yi1Y .

Tested the system with Django1.10 and Django1.11 .

With Django1.10 everything works. With Django1.11 we have the error.

I finally solved my problem.

The problem is: If a user just get a 404 page, a new CSRF Token is generated, invalidating the CSRF Token that was originally loaded with <% csrf_token %>.

How I’ve discovered

On the WebSite that I work, we have a page with the URI /en/courses/ .

On that page, on the .html file we include a JavaScript:

The app.js was trying to load a file named assets/js/particles.json using the relative path, so the final URL of the static file was /en/courses/assets/js/particles.json . Load the particles.json is the only thing that app.js was doing. Nothing else.

That particles.json doesn’t exist on our system.

After successfully load /en/courses/ , the Django Server was receiving a request for /en/courses/assets/js/particles.json that raises a 404 error for the static file, but this error 404 is not even noticed by the users because this JS file was doing nothing.

After I remove this , everything worked fine.

Then with debugs on the django.middleware.csrf.CsrfViewMiddleware I could confirm that if I reload a page 1000 times, the CSRF Token returned by _unsalt_cipher_token (​ ​ https://github.com/django/django/blob/stable/1.11.x/django/middleware/csrf.py#L62) is always the same. But if I just try to access a page that doesn’t exist, then _unsalt_cipher_token returns a different value (a new token is generated).

Unbelievable that a single javascript that doesn’t even exist has broken my system and took me 3 days to find out.

Источник

CSRF error on all POST requests #1912

I have set up weblate using the documentation without docker. It is running from a virtualenv, served by gunicorn with an nginx in front of it. HTTPS is set up in front (I am using correct.example.com here for the correct HTTPS hostname), the following settings are changed from the default settings:

Expected behaviour

Actual behaviour

When I attempt a login: «CSRF verification failed. Request aborted.»

I have observed the following:

  • Every time I reload, the CSRF token in the HTML changes even when I have CSRF_USE_SESSIONS = True . The session cookie stays identical.
  • On a single response, the «Set-cookie: csrftoken» header and the CSRF token in the HTML is different when I have CSRF_USE_SESSIONS = False
  • ENABLE_HTTPS = False or CSRF_COOKIE_SECURE = False do not help
  • With debugging enabled, I can see the following log messages:
    lib/python2.7/site-packages/django/template/defaulttags.py:66: UserWarning: A <% csrf_token %>was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext. as well as Forbidden (Referer checking failed — https://correct.example.com/ does not match any trusted origins.): /accounts/register/

Server configuration

Please paste the output of command ./manage.py list_versions over here

  • Weblate 2.19.1
  • Python 2.7.5
  • Django 1.11.11
  • six 1.11.0
  • social-auth-core 1.7.0
  • social-auth-app-django 2.1.0
  • django-appconf 1.0.2
  • Translate Toolkit 2.3.0
  • Whoosh 2.7.4
  • defusedxml 0.5.0
  • Git 1.8.3.1
  • Pillow (PIL) 1.1.7
  • dateutil 2.7.0
  • lxml 4.2.0
  • django-crispy-forms 1.7.2
  • compressor 2.2
  • djangorestframework 3.7.7
  • user-agents 1.1.0
  • pytz 2018.3
  • pyuca N/A
  • python-bidi 0.4.0
  • pyLibravatar N/A
  • PyYAML 3.12
  • Database backends: django.db.backends.mysql

Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

The text was updated successfully, but these errors were encountered:

Источник

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

Гене…

Подробнее

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 ()

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

Понравилась статья? Поделить с друзьями:
  • Django admin csrf error
  • Django 500 error ajax
  • Django 400 error
  • Displayname field missing from registry как исправить
  • Displaying bus initialization error messages