django - other_dict 必须是一个映射(类字典)对象

标签 django django-templates

我有以下上下文处理器:

def btc_price(request):
    price = get_price()
    return {'btc_price', price}

如果重要,这是我的 get_price 函数:
def get_price():
    now = datetime.datetime.now()
    if PriceCache.objects.all().exists():
        last_fetch = PriceCache.objects.latest('time_fetched')
        time_last_fetched = last_fetch.time_fetched
        day = datetime.timedelta(days=1)

        if now - time_last_fetched > day:
            api_url = urllib2.Request("https://www.bitstamp.net/api/ticker/")
            opener = urllib2.build_opener()
            f = opener.open(api_url)
            fetched_json = json.loads(f.read())
            cost_of_btc = fetched_json['last']

            PriceCache.objects.create(price=cost_of_btc, time_fetched=now)
            last_fetch.delete()
            return cost_of_btc
        else:
            return last_fetch.price
    else:
        api_url = urllib2.Request("https://www.bitstamp.net/api/ticker/")
        opener = urllib2.build_opener()
        f = opener.open(api_url)
        fetched_json = json.loads(f.read())
        cost_of_btc = fetched_json['last']

        PriceCache.objects.create(price=cost_of_btc, time_fetched=now)
    return cost_of_btc

我已经在 TEMPLATE_CONTEXT_PROCESSORS 中声明了上下文处理器,它看起来像:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
"Computer_store.processors.btc_price",
)

并且在我的 render_to_response 函数中正确定义了请求上下文。
return render_to_response('home.html', {}, context_instance = RequestContext(request))

但是,当我尝试在主页上运行此代码时,出现一个奇怪的错误。TypeError at / other_dict must be a mapping (dictionary-like) object.
完整的回溯可用 here

最佳答案

看起来像

return {'btc_price', price}

应该变成:
return {'btc_price': price}

关于django - other_dict 必须是一个映射(类字典)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16849031/

相关文章:

python - 在使用 UUID 字段作为主字段的 Django 模型中添加非主键自动字段或 'serial' 字段

Django 管理页面布局随新版本而更改

javascript - 使用 JSON.parse 时,我在位置 1 处收到 JSON 中的 "SyntaxError: Unexpected token '

django - 动态表单字段集

django - Django View 中表单提交的不同重定向

django - 如何在 Django 中将列表项插入数据库?

javascript - 使用 javascript django 的带有图像的推文的工作示例

python - Django:测试发送的邮件内容

django - 无法将 extra_context 添加到 ListView

Django - 使用 postgres 后端返回不同结果集的所有关联行