Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the full/absolute URL (with domain) in Django?

Tags:

django

How can I get the full/absolute URL (e.g. https://example.com/some/path) in Django without the Sites module? That's just silly... I shouldn't need to query my DB to snag the URL!

I want to use it with reverse().

like image 337
mpen Avatar asked Feb 27 '10 00:02

mpen


People also ask

How can we do URL mapping in Django?

Now, start the server and enter localhost:8000/hello to the browser. This URL will be mapped into the list of URLs and then call the corresponding function from the views file. In this example, hello will be mapped and call hello function from the views file. It is called URL mapping.

How can we handle URL in Django?

Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against path_info . Once one of the URL patterns matches, Django imports and calls the given view, which is a Python function (or a class-based view).


2 Answers

Use handy request.build_absolute_uri() method on request, pass it the relative url and it'll give you full one.

By default, the absolute URL for request.get_full_path() is returned, but you can pass it a relative URL as the first argument to convert it to an absolute URL.

>>> request.build_absolute_uri() 'https://example.com/music/bands/the_beatles/?print=true' >>> request.build_absolute_uri('/bands/?print=true') 'https://example.com/bands/?print=true' 
like image 119
Dmitry Shevchenko Avatar answered Nov 11 '22 07:11

Dmitry Shevchenko


If you want to use it with reverse() you can do this : request.build_absolute_uri(reverse('view_name', args=(obj.pk, )))

like image 32
ébewè Avatar answered Nov 11 '22 08:11

ébewè