【问题标题】:Send variables to a template from setting.py从 setting.py 将变量发送到模板
【发布时间】:2020-07-17 12:27:32
【问题描述】:

我正在尝试将 settings.py 中的两个变量发送到模板。在 settings.py 的末尾,我放了变量:

settings.py

.
.
.
# MapBox Studio
mapbox_user = 'a_string'
mapbox_token = 'a_string'

然后我创建了一个 context_processors:

context_processors.py

from django.conf import settings

def mapbox_data(request):
    mapbox_user = settings.mapbox_user
    mapbox_token = settings.mapbox_token
    context = {
        'mapbox_user': mapbox_user,
        'mapbox_token': mapbox_token,
    }
    return context

最后我把它放在了 context_processors 列表中:

    'context_processors': [
        'django.template.context_processors.debug',
        'django.template.context_processors.request',
        'django.contrib.auth.context_processors.auth',
        'django.contrib.messages.context_processors.messages',
        # project context
        'webgis.context_processors.mapbox_data',
    ],

现在我在模板中使用{{ mapbox_user }}{{ mapbox_token }}

var outDoors = new ol.layer.Tile({
  type: 'base',
  title: 'Topographic',
  visible: true,
  source: new ol.source.XYZ({
      attributions: 'powered with <a href="https://openlayers.org/" target="_blank">OpenLayers</a>',
      url: 'https://api.mapbox.com/styles/v1/{{ mapbox_user }}/'
          + 'cjxkimp5j5s0o1ct4b68n4x1p/tiles/256/{z}/{x}/{y}?'
          + 'access_token={{ mapbox_token }}'
    }),
});

但是我看到了这个错误:

AttributeError: 'Settings' 对象没有属性 'mapbox_user'

这是我第一次尝试将数据从 settings.py 传递到模板。我做错了什么? 如果我直接在 HTML 中使用 mapbox_usermapbox_token,我可以毫无问题地查看我的地图。

【问题讨论】:

    标签: javascript python django django-templates mapbox


    【解决方案1】:

    您需要在settings.py 文件中以大写形式声明变量。

    使用

    MAPBOX_USER = 'a_string'
    MAPBOX_TOKEN = 'a_string'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-10
      • 2015-02-18
      • 1970-01-01
      • 1970-01-01
      • 2013-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多