如何在 Django 2 模板中生成绝对 URL
How to generate absolute urls in Django 2 templates
我有一个 html 模板,用于呈现电子邮件,在该模板中,我想附加验证 links。
我正在使用以下代码生成 link
{% url 'verify_email' token=token email=email %}
但是这个生成以下 URL 而不是绝对 URL。
我阅读了这个 SO 线程
- How can I get the full/absolute URL (with domain) in Django?
和一些初步的 google 结果,但所有这些结果看起来都很旧并且对我不起作用。
TLDR: 如何在 Django2 模板文件中生成绝对 URLs
您可以使用其他线程中引用的 build_absolute_uri()
并注册自定义模板标签。只要模板上下文处理器中包含 django.template.context_processors.request
,就会在上下文中提供请求(通过 takes_context
启用)。
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))
更多关于在哪里以及如何做到这一点的信息in the docs。
然后您可以像这样在模板中使用标签:
{% absolute_url 'verify_email' token=token email=email %}
我有一个 html 模板,用于呈现电子邮件,在该模板中,我想附加验证 links。
我正在使用以下代码生成 link
{% url 'verify_email' token=token email=email %}
但是这个生成以下 URL 而不是绝对 URL。
我阅读了这个 SO 线程
- How can I get the full/absolute URL (with domain) in Django?
和一些初步的 google 结果,但所有这些结果看起来都很旧并且对我不起作用。
TLDR: 如何在 Django2 模板文件中生成绝对 URLs
您可以使用其他线程中引用的 build_absolute_uri()
并注册自定义模板标签。只要模板上下文处理器中包含 django.template.context_processors.request
,就会在上下文中提供请求(通过 takes_context
启用)。
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))
更多关于在哪里以及如何做到这一点的信息in the docs。
然后您可以像这样在模板中使用标签:
{% absolute_url 'verify_email' token=token email=email %}