Search code examples
pythondjangodjango-2.1

How to generate absolute urls in Django 2 templates


I have an html template, which is used to render an email, in that template, I want to attach verification links.

I am using the following code to generate the link

{% url 'verify_email' token=token email=email %}

but this one generates following URL instead of absolute URL.

enter image description here

I read this SO thread

and some initial google results but all of them seems old and not working for me.

TLDR: How do I generate absolute URLs in Django2 template files


Solution

  • You can use the build_absolute_uri() referenced in the other thread and register a custom template tag. Request is supplied in the context (that you enable via takes_context) as long as you have django.template.context_processors.request included in your templates context processors.

    from django import template
    from django.shortcuts import reverse
    
    register = template.Library()
    
    @register.simple_tag(takes_context=True)
    def absolute_url(context, view_name, *args, **kwargs):
        request = context['request']
        return request.build_absolute_uri(reverse(view_name, args=args, kwargs=kwargs))
    

    More on where and how to do that in the docs.

    Then you can use the tag in your template like this:

    {% absolute_url 'verify_email' token=token email=email %}