Python 如何在 Django 模板中获取 base_url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28617282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:31:22  来源:igfitidea点击:

How to get getting base_url in django template

pythondjango

提问by David542

Given a website, how would you get the HOST of that in a django template, without passing that var from the view?

给定一个网站,您如何在 Django 模板中获取该网站的 HOST,而不从视图中传递该变量?

http://google.com/hello --> {{ BASE_URL }} ==> 'http://google.com'

采纳答案by Elwin

This has been answered extensively in the following post

这已在以下帖子中得到广泛回答

There are several ways of doing it:

有几种方法可以做到:

  1. As david542 described **
  2. Using {{ request.get_host }} in your template **
  3. Using the contrib.sites framework
  1. 正如 david542 所描述的 **
  2. 在模板中使用 {{ request.get_host }} **
  3. 使用 contrib.sites 框架

** Please note these can be spoofed

** 请注意这些可能被欺骗

回答by David542

You can get the requestobject in your template by adding in the following TEMPLECT_CONTEXT_PROCESSORmiddleware in your settings:

您可以request通过TEMPLECT_CONTEXT_PROCESSOR在设置中添加以下中间件来获取模板中的对象:

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
)

Here is some documentationon it. Then you can call in your template:

这里有一些关于它的文档。然后你可以调用你的模板:

{{ request.META.HTTP_NAME }}

And that will give you the base url.

这将为您提供基本网址。

回答by Aishwarya kabadi

In your template to get base url

在您的模板中获取基本网址

{{ request.get_host }}