{% url url_name %}
gives a relative name.
How can I do something like {% absolute_url url_name %}
so that it returns url with base (including port if present)?
To get the full or absolute URL (with domain) in Python Django, we can use the build_absolute_uri method. to call request. build_absolute_uri with reverse('view_name', args=(obj.pk, ) to get the path of the view with reverse . Then we call “request.
the reverse function allows to retrieve url details from url's.py file through the name value provided there. This is the major use of reverse function in Django. Syntax: Web development, programming languages, Software testing & others. from django.urls import reverse.
What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.
{% url 'contact-form' %} is a way to add a link to another one of your pages in the template. url tells the template to look in the URLs.py file. The thing in the quotes to the right, in this case contact-form , tells the template to look for something with name=contact-form .
There are different solutions. Write your own templatetag and use HttpRequest.build_absolute_uri(location)
. But another way, and a bit hacky.
<a href="{{ request.scheme }}://{{ request.get_host }}{% url url_name %}">click here</a>
Edit: So I'm kinda confused this still gets me upvotes. I currently find this really hacky. Writing an own template tags has gotten a lot easier, so hereby the example for your own tag.
from django import template from django.urls import reverse register = template.Library() @register.simple_tag(takes_context=True) def abs_url(context, view_name, *args, **kwargs): # Could add except for KeyError, if rendering the template # without a request available. return context['request'].build_absolute_uri( reverse(view_name, args=args, kwargs=kwargs) ) @register.filter def as_abs_url(path, request): return request.build_absolute_uri(path)
Examples:
<a href='{% abs_url view_name obj.uuid %}'> {% url view_name obj.uuid as view_url %} <a href='{{ view_url|as_abs_url:request }}'>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With