How can I get the full/absolute URL (with domain) in Django?
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'
If you can't get access to request
then you can't use get_current_site(request)
as recommended in some solutions here. You can use a combination of the native Sites framework and get_absolute_url
instead. Set up at least one Site in the admin, make sure your model has a get_absolute_url() method, then:
>>> from django.contrib.sites.models import Site
>>> domain = Site.objects.get_current().domain
>>> obj = MyModel.objects.get(id=3)
>>> path = obj.get_absolute_url()
>>> url = 'http://{domain}{path}'.format(domain=domain, path=path)
>>> print(url)
'http://example.com/mymodel/objects/3/'
https://docs.djangoproject.com/en/dev/ref/contrib/sites/#getting-the-current-domain-for-full-urls
If you want to use it with reverse()
you can do this : request.build_absolute_uri(reverse('view_name', args=(obj.pk, )))