1

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

Shobi
  • 10,374
  • 6
  • 46
  • 82

1 Answers1

4

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 %}
Community
  • 1
  • 1
petr
  • 1,099
  • 1
  • 10
  • 23
  • `Unsolved reverence 'context'` error for this line of code: `equest = context['request']` How to fix this? – Nairum Aug 06 '19 at 16:32
  • See https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/ for the code example with `takes_context=True`. – petr Aug 08 '19 at 08:20