How to reverse a name to a absolute url in django template?
In template I use this to print absolute URL with protocol, host and port if present:
<a href="{{ request.scheme }}://{{ request.get_host }}{% url url_name %}">link</a>
In Python I use:
from django.core.urlresolvers import reverse
def do_something(request):
link = "{}://{}{}".format(request.scheme, request.get_host(), reverse('url_name', args=(some_arg1,)))
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 }}'>
You can use the build_absolute_uri()
method in the request object. In template use this as request.build_absolute_uri
. This will create the absolute address including protocol, host and port.
Example:
<a href="{{request.build_absolute_uri}}">click here</a>