How to reverse a name to a absolute url in django template?

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="https://stackoverflow.com/questions/19024159/{% abs_url view_name obj.uuid %}">

{% url view_name obj.uuid as view_url %}
<a href="{{ view_url|as_abs_url:request }}">

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)