How to get full url from django request

Is there a better way to get the full url in django than doing the following:

url = request.META['HTTP_HOST'] + request.META['PATH_INFO'] + request.META['QUERY_STRING'] 

Is there something like request.META['URL'] ?

+5
source share
2 answers

You can get the full url using the request.build_absolute_uri method:

 FULL_URL_WITH_QUERY_STRINg: request.build_absolute_uri() FULL_URL: request.build_absolute_uri('?') ABSOLUTE_ROOT: request.build_absolute_uri('/')[:-1].strip("/") ABSOLUTE_ROOT_URL: request.build_absolute_uri('/').strip("/") 

If it helps you.

The best way to use ABSOLUTE URLs in Django, you can create context_processors or middleware and find your ABSOLUTE_URL and return it so you can use any place in django.

Like this example:

 def absolute(request): urls = { 'ABSOLUTE_ROOT': request.build_absolute_uri('/')[:-1].strip("/"), 'ABSOLUTE_ROOT_URL': request.build_absolute_uri('/').strip("/"), } return urls 

And then you should use {{ABSOLUTE_ROOT}} anywhere in your django template.

+10
source

Source: https://habr.com/ru/post/1207099/


All Articles