680π
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'
139π
If you want to use it with reverse()
you can do this : request.build_absolute_uri(reverse('view_name', args=(obj.pk, )))
- [Django]-Django dynamic forms β on-the-fly field population?
- [Django]-Django: guidelines for speeding up template rendering performance
- [Django]-Allowing RabbitMQ-Server Connections
90π
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 = f'https://{domain}{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
- [Django]-Django index page best/most common practice
- [Django]-Many-To-Many Fields View on Django Admin
- [Django]-Django DRF with oAuth2 using DOT (django-oauth-toolkit)
77π
You can also use get_current_site
as part of the sites app (from django.contrib.sites.models import get_current_site
). It takes a request object, and defaults to the site object you have configured with SITE_ID
in settings.py if request is None
. Read more in documentation for using the sites framework
e.g.
from django.contrib.sites.shortcuts import get_current_site
request = None
full_url = ''.join(['http://', get_current_site(request).domain, obj.get_absolute_url()])
It isnβt as compact/neat as request.build_absolute_url()
, but it is usable when request objects are unavailable, and you have a default site url.
- [Django]-Django: Arbitrary number of unnamed urls.py parameters
- [Django]-Migrating Django fixtures?
- [Django]-Django py.test does not find settings module
26π
If you donβt want to hit the database, you could do it with a setting. Then, use a context processor to add it to every template:
# settings.py (Django < 1.9)
...
BASE_URL = 'http://example.com'
TEMPLATE_CONTEXT_PROCESSORS = (
...
'myapp.context_processors.extra_context',
)
# settings.py (Django >= 1.9)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
# Additional
'myapp.context_processors.extra_context',
],
},
},
]
# myapp/context_processors.py
from django.conf import settings
def extra_context(request):
return {'base_url': settings.BASE_URL}
# my_template.html
<p>Base url is {{ base_url }}.</p>
- [Django]-Pagination in Django-Rest-Framework using API-View
- [Django]-What does 'many = True' do in Django Rest FrameWork?
- [Django]-Django-allauth: Linking multiple social accounts to a single user
26π
In your view, just do this:
base_url = "{0}://{1}{2}".format(request.scheme, request.get_host(), request.path)
- [Django]-How to combine multiple QuerySets in Django?
- [Django]-No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
- [Django]-Django admin and MongoDB, possible at all?
20π
This worked for me in my template:
{{ request.scheme }}://{{ request.META.HTTP_HOST }}{% url 'equipos:marca_filter' %}
I needed the full url to pass it to a js fetch function.
I hope this help you.
- [Django]-How to force application version on AWS Elastic Beanstalk
- [Django]-Django F() division β How to avoid rounding off
- [Django]-Change a field in a Django REST Framework ModelSerializer based on the request type?
18π
django-fullurl
If youβre trying to do this in a Django template, Iβve released a tiny PyPI package django-fullurl
to let you replace url
and static
template tags with fullurl
and fullstatic
, like this:
{% load fullurl %}
Absolute URL is: {% fullurl "foo:bar" %}
Another absolute URL is: {% fullstatic "kitten.jpg" %}
These badges should hopefully stay up-to-date automatically:
In a view, you can of course use request.build_absolute_uri
instead.
- [Django]-Jquery template tags conflict with Django template!
- [Django]-Django rest framework: query parameters in detail_route
- [Django]-Factory-boy create a list of SubFactory for a Factory
13π
Yet another way. You could use build_absolute_uri()
in your view.py
and pass it to the template.
view.py
def index(request):
baseurl = request.build_absolute_uri()
return render_to_response('your-template.html', { 'baseurl': baseurl })
your-template.html
{{ baseurl }}
- [Django]-Iterating over related objects in Django: loop over query set or use one-liner select_related (or prefetch_related)
- [Django]-Django-rest-framework returning 403 response on POST, PUT, DELETE despite AllowAny permissions
- [Django]-Django: Multiple forms possible when using FormView?
11π
Examine Request.META
dictionary that comes in. I think it has server name and server port.
- [Django]-Django apps aren't loaded yet when using asgi
- [Django]-Django select_for_update cannot be used outside of a transaction
- [Django]-Nginx doesn't serve static
- [Django]-Equivalent of PHP "echo something; exit();" with Python/Django?
- [Django]-Substring in a django template?
- [Django]-Error: could not determine PostgreSQL version from '10.3' β Django on Heroku
10π
To create a complete link to another page from a template, you can use this:
{{ request.META.HTTP_HOST }}{% url 'views.my_view' my_arg %}
request.META.HTTP_HOST gives the host name, and url gives the relative name. The template engine then concatenates them into a complete url.
- [Django]-ModuleNotFoundError: No module named 'grp' on windows
- [Django]-Separation of business logic and data access in django
- [Django]-Celery : Execute task after a specific time gap
7π
If youβre using django REST framework, you can use the reverse function from rest_framework.reverse
. This has the same behavior as django.core.urlresolvers.reverse
, except that it uses a request parameter to build a full URL.
from rest_framework.reverse import reverse
# returns the full url
url = reverse('view_name', args=(obj.pk,), request=request)
# returns only the relative url
url = reverse('view_name', args=(obj.pk,))
Edited to mention availability only in REST framework
- [Django]-Querying django migrations table
- [Django]-What's the idiomatic Python equivalent to Django's 'regroup' template tag?
- [Django]-Extend base.html problem
6π
I know this is an old question. But I think people still run into this a lot.
There are a couple of libraries out there that supplement the default Django functionality. I have tried a few. I like the following library when reverse referencing absolute urls:
https://github.com/fusionbox/django-absoluteuri
Another one I like because you can easily put together a domain, protocol and path is:
https://github.com/RRMoelker/django-full-url
This library allows you to simply write what you want in your template, e.g.:
{{url_parts.domain}}
- [Django]-Django: Safely Remove Old Migrations?
- [Django]-Add a custom button to a Django application's admin page
- [Django]-Django: Fat models and skinny controllers?
5π
If anyone is interested in fetching the absolute reverse url with parameters in a template , the cleanest way is to create your own absolute version of the {% url %}
template tag by extending and using existing default code.
Here is my code:
from django import template
from django.template.defaulttags import URLNode, url
register = template.Library()
class AbsURLNode(URLNode):
def __init__(self, view_name, args, kwargs, asvar):
super().__init__(view_name, args, kwargs, asvar)
def render(self, context):
url = super().render(context)
request = context['request']
return request.build_absolute_uri(url)
@register.tag
def abs_url(parser, token):
urlNode = url(parser, token)
return AbsURLNode( urlNode.view_name, urlNode.args, urlNode.kwargs, urlNode.asvar )
Usage in templates:
{% load wherever_your_stored_this_tag_file %}
{% abs_url 'view_name' parameter %}
will render(example):
http://example.com/view_name/parameter/
instead of
/view_name/parameter/
- [Django]-How to test "render to template" functions in django? (TDD)
- [Django]-Django Generic Views using decorator login_required
- [Django]-Django Form File Field disappears on form error
3π
I got it:
wsgiref.util.request_uri(request.META)
Get the full uri with schema, host, port path and query.
- [Django]-How to recursively query in django efficiently?
- [Django]-Adding to the "constructor" of a django model
- [Django]-How to deal with "SubfieldBase has been deprecated. Use Field.from_db_value instead."
3π
You can either pass request reverse('view-name', request=request)
or enclose reverse() with build_absolute_uri request.build_absolute_uri(reverse('view-name'))
- [Django]-What is a "slug" in Django?
- [Django]-What is a django.utils.functional.__proxy__ object and what it helps with?
- [Django]-How to go from django image field to PIL image and back?
3π
Not for absolute url but I was looking just to get host. If you want to get host in your view.py you can do
def my_view(request):
host = f"{ request.scheme }://{ request.META.get('HTTP_HOST') }"
- [Django]-Django character set with MySQL weirdness
- [Django]-Django β How to pass several arguments to the url template tag
- [Django]-Django Framework β Is there a shutdown event that can be subscribed to?
2π
As mentioned in other answers, request.build_absolute_uri()
is perfect if you have access to request
, and sites
framework is great as long as different URLs point to different databases.
However, my use case was slightly different. My staging server and the production server access the same database, but get_current_site
both returned the first site
in the database. To resolve this, you have to use some kind of environment variable. You can either use 1) an environment variable (something like os.environ.get('SITE_URL', 'localhost:8000')
) or 2) different SITE_ID
s for different servers AND different settings.py.
Hopefully someone will find this useful!
- [Django]-Negating a boolean in Django template
- [Django]-Django custom field validator vs. clean
- [Django]-Django staticfiles not found on Heroku (with whitenoise)
2π
I came across this thread because I was looking to build an absolute URI for a success page. request.build_absolute_uri()
gave me a URI for my current view but to get the URI for my success view I used the followingβ¦.
request.build_absolute_uri(reverse(βsuccess_view_nameβ))
- [Django]-How to add a cancel button to DeleteView in django
- [Django]-How do you dynamically hide form fields in Django?
- [Django]-405 "Method POST is not allowed" in Django REST framework
2π
While working on a project I came to know to get the full/absolute URL in Django.
If your URL looks like this in the address bar:
https://stackoverflow.com/questions/2345708
And if you want to show the above URL to your template.
{{ request.path }}
#Without GET parameters.
{{ request.get_full_path }}
#with GET parameters
For the above two codes, this will print in your template will be
questions/2345708
and another way to get a full URL is:
{{request.build_absolute_uri}}
this will print in your template will be:
https://stackoverflow.com/questions/2345708
- [Django]-How to get superuser details in Django?
- [Django]-Django admin default filter
- [Django]-Django form fails validation on a unique field
1π
There is also ABSOLUTE_URL_OVERRIDES available as a setting
https://docs.djangoproject.com/en/2.1/ref/settings/#absolute-url-overrides
But that overrides get_absolute_url(), which may not be desirable.
Instead of installing sites framework just for this or doing some of the other stuff mentioned here that relies on request object, I think the better solution is to place this in models.py
Define BASE_URL in settings.py, then import it into models.py and make an abstract class (or add it to one youβre already using) that defines get_truly_absolute_url(). It could be as simple as:
def get_truly_absolute_url(self):
return BASE_URL + self.get_absolute_url()
Subclass it and now you can use it everywhere.
- [Django]-Querying django migrations table
- [Django]-How do you dynamically hide form fields in Django?
- [Django]-Separating form input and model validation in Django?
1π
<div class='col-12 col-md-6'>
<p class='lead'>Login</p>
{% include 'accounts/snippets/form.html' with form=login_form next_url=request.build_absolute_uri %}
</div>
Here for example am saying load the form and tell the form that the next URL is the current URL which this code rendred from
- [Django]-Detect mobile, tablet or Desktop on Django
- [Django]-ModuleNotFoundError: No module named 'grp' on windows
- [Django]-How to make two django projects share the same database
1π
I use this code :
request.build_absolute_uri('/')[:-1]
response :
https://yourdomain.com
- [Django]-Negating a boolean in Django template
- [Django]-Multiple annotate Sum terms yields inflated answer
- [Django]-Get object by field other than primary key
- [Django]-What is "load url from future" in Django
- [Django]-Override existing Django Template Tags
- [Django]-Django ignores router when running tests?
- [Django]-Name '_' is not defined
- [Django]-PyCharm: DJANGO_SETTINGS_MODULE is undefined
- [Django]-Django form: what is the best way to modify posted data before validating?
0π
If request is around, there are good answers. Thereβs also good answers on how to obtain it in the template. Here a simple option for accessing the url in the backend.
in settings.py:
ABSOLUTE_URL_BASE = "http://yourdomain.com"
in models.py or wherever:
from django.conf import settings
from django.urls import reverse
url = settings.ABSOLUTE_URL_BASE + reverse("app:name")
One could also use this set-up to create a templatetag.
- [Django]-Altering one query parameter in a url (Django)
- [Django]-Django: Arbitrary number of unnamed urls.py parameters
- [Django]-Using Cloudfront with Django S3Boto
-2π
class WalletViewSet(mixins.ListModelMixin, GenericViewSet):
serializer_class = WalletSerializers
pagination_class = CustomPaginationInvestment
def get_queryset(self):
######################################################
print(self.request.build_absolute_uri())
#####################################################
wallet, created = Wallet.objects.get_or_create(owner=self.request.user)
return Wallet.objects.filter(id=wallet.id)
You get output like this
http://localhost:8000/v1/wallet
HTTP GET /v1/wallet 200 [0.03, 127.0.0.1:41608]
- [Django]-Macros in django templates
- [Django]-How do I POST with jQuery/Ajax in Django?
- [Django]-Django Installed Apps Location
-3π
You can also use:
import socket
socket.gethostname()
This is working fine for me,
Iβm not entirely sure how it works. I believe this is a bit more low level and will return your server hostname, which might be different than the hostname used by your user to get to your page.
- [Django]-405 "Method POST is not allowed" in Django REST framework
- [Django]-Unittest Django: Mock external API, what is proper way?
- [Django]-Django: Error: You don't have permission to access that port
- [Django]-What is the purpose of adding to INSTALLED_APPS in Django?
- [Django]-Update all models at once in Django
- [Django]-Custom django admin templates not working