【问题标题】:How to get getting base_url in django template如何在 django 模板中获取 base_url
【发布时间】:2015-04-21 10:35:46
【问题描述】:

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

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

【问题讨论】:

    标签: python django


    【解决方案1】:

    这些其他答案都没有考虑到方案。这对我有用:

    {{ request.scheme }}://{{ request.get_host }}
    

    【讨论】:

      【解决方案2】:

      网址:google.com/hello

      在模板中:

      {{ request.get_full_path() }}
      return /hello
      
      OR
      
      {{ request.get_host() }}
      return google.com
      

      鉴于:

      from django.contrib.sites.shortcuts import get_current_site
      
      def home(request):
          get_current_site(request)
          # google.com
      
          # OR
          request.get_host()
          # google.com
      
          # OR
          request.get_full_path()
          # /hello
      

      【讨论】:

        【解决方案3】:

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

        {{ request.get_host() }}
        

        【讨论】:

          【解决方案4】:

          这已在以下post中得到了广泛的回答

          有几种方法:

          1. 正如 david542 所述**
          2. 在您的模板中使用 {{ request.get_host() }} **
          3. 使用contrib.sites 框架

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

          【讨论】:

          • 感谢您提供全面的答案/选项。能否请您补充一下“如何”欺骗前两个?
          • 前两个依赖于请求元数据,它本质上来自浏览器。这可以通过允许的主机设置来解决,更多信息可以在这里找到docs.djangoproject.com/en/1.7/ref/settings/#allowed-hosts
          【解决方案5】:

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

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

          这里有一些documentation。然后你可以调用你的模板:

          {{ request.META.HTTP_NAME }}
          

          这将为您提供基本网址。

          【讨论】:

            猜你喜欢
            • 2011-04-16
            • 2015-02-20
            • 2011-11-22
            • 1970-01-01
            • 1970-01-01
            • 2011-11-11
            • 2011-02-10
            • 2011-02-22
            相关资源
            最近更新 更多