Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read variables added to RequestContext inside class-based generic views?

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.
like image 229
Alex Bolotov Avatar asked Mar 04 '11 01:03

Alex Bolotov


2 Answers

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.

like image 64
jacobian Avatar answered Nov 10 '22 00:11

jacobian


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

like image 32
lprsd Avatar answered Nov 10 '22 01:11

lprsd