Django上下文处理器“str”对象不是callab

2024-05-13 23:07:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用上下文处理器构建动态侧边栏。我从数据库表中为边栏获取不同的值。在

这是我的上下文处理器:

from clients.models import client
def sidebar(request):
        return {'clientlist': client.objects.order_by('name').distinct('name')}

在视图.py我有以下代码:

^{pr2}$

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声明。我本想避免这种情况,结果被卡住了。请帮我找出这个错误。在


Tags: nameinpyclient视图indexreturnobjects
1条回答
网友
1楼 · 发布于 2024-05-13 23:07:13

如果您希望clientlist包含在所有视图中,那么请将client.models.sidebar添加到TEMPLATE_CONTEXT_PROCESSORS设置中,并从视图中的render调用中删除{}参数-使用render快捷方式时,模板将自动与请求上下文一起呈现。在

def index(request):
    allclientlist = Client.objects.all()
    return render(request, 'clients/index.html', {'allclientlist': allclientlist})

顺便说一句,Django约定是将侧栏上下文处理器移到client.context_processors模块中,并将模型大写为Client。在

相关问题 更多 >