[Django]-How to reverse a name to a absolute url in django template?

57πŸ‘

βœ…

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 }}'>
πŸ‘€Blackeagle52

20πŸ‘

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>
πŸ‘€Aneesh R S

11πŸ‘

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,)))
πŸ‘€igo

0πŸ‘

I use a custom tag absurl and the context processor django.template.context_processors.request. For instance:

Custom tag defined in tenplatetags\mytags.py:

from django import template
register = template.Library()

@register.simple_tag(takes_context=True)
def absurl(context, object):
    return context['request'].build_absolute_uri(object.get_absolute_url())

In settings.py ensure that you have the following:

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'OPTIONS': {
        'debug': DEBUG,
        'context_processors': [
            ...
            'django.template.context_processors.request',
            ...

Then ensure the model has a build_absolute_url, e.g. for use by the admin area:

class ProductSelection(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(unique=True)
    fixed_price = models.DecimalField(max_digits=10, decimal_places=2, ...
    ...

    def get_absolute_url(self):
        return reverse('myapp:selection', args=[self.slug])

The in the template itself use absurl to bind it altogether:

 {% load mytags %}
 ...
 <script type="application/ld+json">{
    "@context": "http://schema.org/",
    "@type": "Product",
    "name": " {{selection.title}}",
    ...
    "offers": {
      "@type": "Offer",
      "priceCurrency": "GBP",
      "url": "{% absurl selection %}",      <--- look here
    } }
  </script>
πŸ‘€shuckc

Leave a comment