简体   繁体   中英

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.

在此处输入图片说明

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

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 %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM