[英]Django context processor - 'str' object is not callable
我正在尝试使用上下文处理器构建动态边栏。 我从数据库表中获取侧边栏的不同值。
这是我的上下文处理器:
from clients.models import client
def sidebar(request):
return {'clientlist': client.objects.order_by('name').distinct('name')}
在views.py中,我有以下代码:
from django.shortcuts import render
from django.template import loader, RequestContext
from clients.models import client
def index(request):
allclientlist = client.objects.all()
return render (request, 'clients/index.html', {'allclientlist': allclientlist}, context_instance=RequestContext(request, processors=['sidebar']))
allclientlist
用于生成包含所有客户端及其数据的表。 接下来,我正在尝试使用上下文处理器构建动态边栏,并获得以下追溯
Traceback:
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/root/projects/webapp/clients/views.py" in index
7. return render (request, 'clients/index.html', {'allclientlist': allclientlist}, context_instance=RequestContext(request, processors=['sidebar']))
File "/usr/local/lib/python2.7/site-packages/django/template/context.py" in __init__
179. self.update(processor(request))
Exception Type: TypeError at /clients/
Exception Value: 'str' object is not callable
它在以下情况下起作用:
def index(request):
allclientlist = client.objects.all()
clientlist = client.objects.order_by('name').distinct('name')
return render(request, 'clients/index.html', {'allclientlist': allclientlist, 'clientlist': clientlist})
但是要使该菜单在所有视图中可用,我需要在所有视图中都有clientlist
声明。 我想避免这种情况并卡住。 请帮助我找到此错误。
如果要在所有视图中都包括clientlist
,则将client.models.sidebar
添加到TEMPLATE_CONTEXT_PROCESSORS
设置中,并从视图中的render
调用中删除context_instance
参数-使用render
快捷方式时,模板将自动与请求上下文一起渲染。
def index(request):
allclientlist = Client.objects.all()
return render(request, 'clients/index.html', {'allclientlist': allclientlist})
client.context_processors
一句,Django约定是将侧边栏上下文处理器移至client.context_processors
模块,并将模型大写为Client
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.