【问题标题】:passing request in django template tag在 Django 模板标签中传递请求
【发布时间】:2017-05-17 06:01:05
【问题描述】:

我试图在我的自定义模板标签函数中访问request。但它不起作用。

views.py

def candidate(request):
   .......
   .......
   return render(request, template, context)

模板标签

@register.simple_tag(takes_context=True)
def make_url(context, doc_url):
    request = context["request"]
    protocol = "https://" if request.is_secure() else "http://"
    host = request.get_host()
    new_url = "%s%s%s" %(protocol, host, doc_url)
    return new_url

模板.html

<iframe src="{{  candidate.resume_file.url | make_url }}" frameborder="0"></iframe>

【问题讨论】:

  • 什么不起作用?您是否收到任何错误消息?
  • 您是在尝试编写自定义模板标签还是自定义过滤器?
  • 感谢您的 cmets。抱歉,我遇到了问题。将 register.filter 更改为 register.simple_tag。我替换了这个 {{ Candidate.resume_file.url | html 中带有 {% make_url Candidate.resume_file.url %} 的 make_url }}
  • 你不应该在你的问题中将“filter”更改为“simple_tag”......这会让其他人,比如我......感到困惑......

标签: django django-templates django-template-filters


【解决方案1】:

Django 过滤器没有对调用它们的上下文进行任何特殊访问,它们只是普通的旧函数。

你需要传入你想在函数中使用的任何东西。

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

来源:Can custom Django filters access request.user?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-15
    • 2012-05-30
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 2011-10-06
    • 2018-12-20
    相关资源
    最近更新 更多