如何在基于类的通用视图中读取添加到 RequestContext 的变量?

发布于 2024-10-19 23:33:44 字数 1132 浏览 3 评论 0原文

使用常规视图,可以像 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_template1

如何读取添加到 基于类的通用视图 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_template1

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

偏爱你一生 2024-10-26 23:33:44

您需要使用回调(在本例中为 get_queryset()),而不是类属性。当您静态控制选项时,类属性实际上只是快捷方式,并且它们仅限于一些非常简单的事情。当您需要做更复杂的事情时,您会想要切换到回调。

在您的情况下,类似以下的代码应该可以工作:

class ArticleListView(ListView):
    template_name = 'stuff_list'

    def get_queryset(self):
        return get_list_or_404(Stuff, foo=self.request.DEBUG)

有关更多详细信息,请参阅文档

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:

class ArticleListView(ListView):
    template_name = 'stuff_list'

    def get_queryset(self):
        return get_list_or_404(Stuff, foo=self.request.DEBUG)

For more details, see the documentation.

仅此而已 2024-10-26 23:33:44

RequestContext 参数也是常规上下文变量。您应该能够执行 {{VARNAME}}

RequestContext parameters are also regular context variables. You should be able to do just {{VARNAME}}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文