如何在基于类的通用视图中读取添加到 RequestContext 的变量?
使用常规视图,可以像 request.VARNAME
一样访问 RequestContext
变量:
def example(request, template_name='stuff_list'):
return render_to_response(template_name,
{'stuff_list': get_list_or_404(Stuff, foo=request.DEBUG)},
context_instance=RequestContext(request))
...而不是设置 context_instance
我可以调用函数基于通用视图 direct_to_template
1
如何读取添加到 基于类的通用视图 2?
例如:
class ArticleListView(ListView):
template_name = 'stuff_list'
bar = request.DEBUG # This won't work. What should I use instead?
queryset = get_list_or_404(Stuff, foo=bar)
1 Will be replaced by class-based
TemplateView
anyway.2 They are new in Django 1.3 and I want to use them just because.
With regular views, RequestContext
variables can be accessed just like request.VARNAME
:
def example(request, template_name='stuff_list'):
return render_to_response(template_name,
{'stuff_list': get_list_or_404(Stuff, foo=request.DEBUG)},
context_instance=RequestContext(request))
... instead of setting context_instance
I could call function-based generic view direct_to_template
1
How do I read variables added to RequestContext inside class-based generic views 2?
For example:
class ArticleListView(ListView):
template_name = 'stuff_list'
bar = request.DEBUG # This won't work. What should I use instead?
queryset = get_list_or_404(Stuff, foo=bar)
1 Will be replaced by class-based
TemplateView
anyway.2 They are new in Django 1.3 and I want to use them just because.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用回调(在本例中为
get_queryset()
),而不是类属性。当您静态控制选项时,类属性实际上只是快捷方式,并且它们仅限于一些非常简单的事情。当您需要做更复杂的事情时,您会想要切换到回调。在您的情况下,类似以下的代码应该可以工作:
有关更多详细信息,请参阅文档。
You need to use a callback —
get_queryset()
in this case — instead of the class attributes. Class attributes are really just shortcuts when you're controlling options statically, and they're limited to some pretty simple things. When you need to do something more complex, you'll want to switch to a callback instead.In your case, code like the following should work:
For more details, see the documentation.
RequestContext 参数也是常规上下文变量。您应该能够执行
{{VARNAME}}
RequestContext parameters are also regular context variables. You should be able to do just
{{VARNAME}}