[Fixed]-Getting the request origin in a Django request

0👍

I strongly advice you to use django-cors-headers. It lets you to define CORS_ORIGIN_WHITELIST which is a list of allowed origins in more pythonic way.

31👍

As for getting the url from request (which is what I was looking for), use request.META['HTTP_REFERER'] instead.

11👍

In Django,

request.headers['Origin']

answers the original question.

You can print(request.headers) to see everything available in the headers.

3👍

Use this:

origin = request.META.get("HTTP_ORIGIN")

This is the way django-cors-headers use it in the middleware:

2👍

you can get it by request.META["HTTP_ORIGIN"]

0👍

To answer the question “Does anyone know where in the Request object I can get the origin of the request?”, would the request.META[‘REMOTE_ADDR’] give you what you need?

0👍

In Django 2.2 use:

request.META.get('HTTP_REFERER')

Make sure that the request property doesn’t have mode = no-cors

see:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin

"There are some exceptions to the above rules; for example, if a cross-origin GET or HEAD request is made in no-cors mode, the Origin header will not be added."

Leave a comment