Django ошибка доступа 403

when I’m using following Python code to send a POST request to my Django website I’m getting 403: Forbidden error.

url = 'http://www.sub.example.com/'
values = { 'var': 'test' }

try:
    data = urllib.urlencode(values, doseq=True)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)
    the_page = response.read()
except:
    the_page = sys.exc_info()
    raise

When I’m opening any other website it works properly.
example.com is Django website too, and it works properly too.
I think, that’s Django config problem, can anyone tell me what should I do to provide access to my script?

Stephen Ostermiller's user avatar

asked Jul 23, 2011 at 14:04

Djent's user avatar

4

Does the view that you are posting to have a Django Form on it? If so, I wonder if it’s giving a csrf error. I think that manifests itself as a 403. In that case, you’d need to add the {{ csrf_token }} tag. Just a thought.

answered Jul 23, 2011 at 14:58

Joe J's user avatar

Joe JJoe J

9,86516 gold badges65 silver badges100 bronze badges

5

The response is 403 because django requires a csrf token (included in the post data) in every POST request you make.

There are various ways to do this such as:

Acquiring the token from cookie and the method has been explained in article enter link description here

or

You can access it from DOM using {{ csrf_token }}, available in the template

So now using the second method:

var post_data = {
  ...
  'csrfmiddlewaretoken':"{{ csrf_token }}"
  ...
}

$.ajax({
  url:'url',
  type:'POST'
  data:post_data,
  success:function(data){
    console.log(data);
  },
  error:function(error){
    console.log(error);
  }
});

chrki's user avatar

chrki

6,1146 gold badges35 silver badges55 bronze badges

answered Jun 19, 2016 at 15:30

Hiro's user avatar

HiroHiro

2,9821 gold badge15 silver badges9 bronze badges

Or you can allow the permission to make this post request.

Note: Should be used in the cases where you don’t need to authenticate the users for posting anything on our server, say, when a new user registers for the first time.

from rest_framework.permissions import AllowAny

class CreateUser(APIView):
    permission_classes = (AllowAny,)
    def post(self, request, format=None):
        return(Response("hi"))

Further Note that, If you want to make that post request form a different domain (in case when the front of the application is in React or angular and the backend is in Django), make sure the add following in the settings file:

  1. Update the INSTALLED_APPS to use ‘coreHeaders’ :

    INSTALLED_APPS = [
    ‘corsheaders’,
    ]

  2. White list your front end domain by adding following to settings file again:

    CORS_ORIGIN_WHITELIST = (
    ‘localhost:8080’,
    )

answered Jun 7, 2017 at 14:37

Santosh Pillai's user avatar

Santosh PillaiSantosh Pillai

8,0891 gold badge31 silver badges27 bronze badges

I got this error when an authentication Token was expired or when no Token was sent with the request. Using a renewed token fixed the problem.

curl -X POST -H "Authorization: Token mytoken" -d "name=myname&age=0" 127.0.0.1:8000/myapi/

or

curl -X POST -H "Authorization: JWT mytoken" -d "name=myname&age=0" 127.0.0.1:8000/myapi/

depending on Token type.

answered Dec 19, 2017 at 23:52

DevB2F's user avatar

DevB2FDevB2F

4,5544 gold badges35 silver badges60 bronze badges

I too had this problem, because I Tried to access the Main endpoint from another endpoint using '../url' URL Jumping.
My Solution was to add another path for the same viewset;

router.register('main/url',ViewSet,'name');
router.register('secondary/url',ViewSet,'name')

But in Your Case You are Trying to access it from a completely different Location, From Django’s Point of view So You need to mark you ViewSet with @crsf_exempt middleware which will Disable Security Protocols Related to CRSF.

answered Apr 12, 2020 at 11:31

ax39T-Venom's user avatar

I’ve had the same problem on Django 1.2.1 FINAL. Since I knew that Django on our production site would never be updated from 1.0 (for various reasons), I found a workaround which I implemented into my development version of settings.py, leaving the production settings.py untouched.

Create a middleware.py file in your application directory with the following code:

class disableCSRF:
    def process_request(self, request):
        setattr(request, '_dont_enforce_csrf_checks', True)
        return None

Then in your development version of settings.py, insert this into MIDDLEWARE_CLASSES:

'your_app_name.middleware.disableCSRF',

Perhaps not the safest solution, but our Django site is strictly internal, so there is a minimum risk for any type of malicious actions. This solution is simple and doesn’t involve changes to templates/views, and it worked instantly (unlike other I’ve tried).

Hopefully someone in a similar situation to mine will find this useful.

Credit goes to John McCollum, on whose site I’ve found this.

Built-in Views¶

Several of Django’s built-in views are documented in
Writing views as well as elsewhere in the documentation.

Serving files in development¶

static.serve(request, path, document_root, show_indexes=False)

There may be files other than your project’s static assets that, for
convenience, you’d like to have Django serve for you in local development.
The serve() view can be used to serve any directory
you give it. (This view is not hardened for production use and should be
used only as a development aid; you should serve these files in production
using a real front-end web server).

The most likely example is user-uploaded content in MEDIA_ROOT.
django.contrib.staticfiles is intended for static assets and has no
built-in handling for user-uploaded files, but you can have Django serve your
MEDIA_ROOT by appending something like this to your URLconf:

from django.conf import settings
from django.urls import re_path
from django.views.static import serve

# ... the rest of your URLconf goes here ...

if settings.DEBUG:
    urlpatterns += [
        re_path(
            r"^media/(?P<path>.*)$",
            serve,
            {
                "document_root": settings.MEDIA_ROOT,
            },
        ),
    ]

Note, the snippet assumes your MEDIA_URL has a value of
'media/'. This will call the serve() view,
passing in the path from the URLconf and the (required) document_root
parameter.

Since it can become a bit cumbersome to define this URL pattern, Django
ships with a small URL helper function static()
that takes as parameters the prefix such as MEDIA_URL and a dotted
path to a view, such as 'django.views.static.serve'. Any other function
parameter will be transparently passed to the view.

Error views¶

Django comes with a few views by default for handling HTTP errors. To override
these with your own custom views, see Customizing error views.

The 404 (page not found) view¶

defaults.page_not_found(request, exception, template_name=‘404.html’)

When you raise Http404 from within a view, Django loads a
special view devoted to handling 404 errors. By default, it’s the view
django.views.defaults.page_not_found(), which either produces a “Not
Found” message or loads and renders the template 404.html if you created it
in your root template directory.

The default 404 view will pass two variables to the template: request_path,
which is the URL that resulted in the error, and exception, which is a
useful representation of the exception that triggered the view (e.g. containing
any message passed to a specific Http404 instance).

Three things to note about 404 views:

  • The 404 view is also called if Django doesn’t find a match after
    checking every regular expression in the URLconf.

  • The 404 view is passed a RequestContext and
    will have access to variables supplied by your template context
    processors (e.g. MEDIA_URL).

  • If DEBUG is set to True (in your settings module), then
    your 404 view will never be used, and your URLconf will be displayed
    instead, with some debug information.

The 500 (server error) view¶

defaults.server_error(request, template_name=‘500.html’)

Similarly, Django executes special-case behavior in the case of runtime errors
in view code. If a view results in an exception, Django will, by default, call
the view django.views.defaults.server_error, which either produces a
“Server Error” message or loads and renders the template 500.html if you
created it in your root template directory.

The default 500 view passes no variables to the 500.html template and is
rendered with an empty Context to lessen the chance of additional errors.

If DEBUG is set to True (in your settings module), then
your 500 view will never be used, and the traceback will be displayed
instead, with some debug information.

The 403 (HTTP Forbidden) view¶

defaults.permission_denied(request, exception, template_name=‘403.html’)

In the same vein as the 404 and 500 views, Django has a view to handle 403
Forbidden errors. If a view results in a 403 exception then Django will, by
default, call the view django.views.defaults.permission_denied.

This view loads and renders the template 403.html in your root template
directory, or if this file does not exist, instead serves the text
“403 Forbidden”, as per RFC 9110#section-15.5.4 (the HTTP 1.1
Specification). The template context contains exception, which is the
string representation of the exception that triggered the view.

django.views.defaults.permission_denied is triggered by a
PermissionDenied exception. To deny access in a
view you can use code like this:

from django.core.exceptions import PermissionDenied


def edit(request, pk):
    if not request.user.is_staff:
        raise PermissionDenied
    # ...

The 400 (bad request) view¶

defaults.bad_request(request, exception, template_name=‘400.html’)

When a SuspiciousOperation is raised in Django,
it may be handled by a component of Django (for example resetting the session
data). If not specifically handled, Django will consider the current request a
‘bad request’ instead of a server error.

django.views.defaults.bad_request, is otherwise very similar to the
server_error view, but returns with the status code 400 indicating that
the error condition was the result of a client operation. By default, nothing
related to the exception that triggered the view is passed to the template
context, as the exception message might contain sensitive information like
filesystem paths.

bad_request views are also only used when DEBUG is False.

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

При попытке входа в админку 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

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

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

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

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

Подробнее

Что такое магические числа?

Это числа происхождение которых непонятно другим программистам и вам спустя некоторое время. Например:

const euros…

Подробнее

Django template индексы в цикле

Для вывода индексов объектов в цикле шаблона Django используется следующий синтаксис:

{% for object in objects_lis…

Подробнее

В чем разница между HTTP методами POST vs PUT vs PATCH?

Прежде всего внимательно ознакомьтесь с определением каждого HTTP метода в статье HTTP request methods.

Теперь кратк…

Подробнее

Посмотреть все пакеты node.js

Все пакеты с зависимостями

npm ls

Все пакеты верхнего уровня

npm ls -depth=0

Подробнее

После обновления >= psycopg 3.1.8 в Django до 4.2.* появляется 502 ошибка

Скорее всего вы не установили всех зависимостей psycopg:

pip install «psycopg[binary,pool]»

Подробнее

Понравилась статья? Поделить с друзьями:
  • Display inf ошибка
  • Django ошибка got an unexpected keyword argument
  • Django ошибка 405
  • Display exe системная ошибка
  • Django ошибка 400