7

I am using django generic views, how do I get access to the request in my template.

URLs:

file_objects = {
    'queryset' : File.objects.filter(is_good=True),
}
urlpatterns = patterns('',
    (r'^files/', 'django.views.generic.list_detail.object_list', dict(file_objects, template_name='files.html')),
)
Mark
  • 2,522
  • 5
  • 36
  • 42

4 Answers4

9

After some more searching, while waiting on people to reply to this. I found:

You need to add this to your settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
)

This means that by default the request will be passed to all templates!

Bite code
  • 578,959
  • 113
  • 301
  • 329
Mark
  • 2,522
  • 5
  • 36
  • 42
  • 4
    Not strictly true - it will be passed to all templates that are rendered using a `RequestContext`, which all generic views are. – Daniel Roseman Aug 31 '10 at 09:14
  • This did not work for me, using Django 1.7 four and a half years later. In fact the 1.7 docs have a warning at the top of https://docs.djangoproject.com/en/1.7/ref/settings/ - "Be careful when you override settings, especially when the default value is a non-empty tuple or dictionary, such as MIDDLEWARE_CLASSES and TEMPLATE_CONTEXT_PROCESSORS. Make sure you keep the components required by the features of Django you wish to use.". However see here for a solution: http://stackoverflow.com/questions/9899113/get-request-session-from-a-class-based-generic-view – Chirael Feb 04 '15 at 02:36
3

Try using the get_queryset method.

def get_queryset(self):
    return Post.objects.filter(author=self.request.user)

see link (hope it helps):- See Greg Aker's page...

  • great! This is very bad documented in Django. I exactly need the request obj. in the Listview subclass. – Timo Oct 29 '14 at 20:09
  • Link is dead, but it's here on web.archive.org: http://web.archive.org/web/20160923030156/http://www.gregaker.net/2012/apr/20/how-does-djangos-class-based-listview-work/ – miyalys Jun 08 '21 at 09:26
3

None of the answers given solved my issue, so for those others who stumbled upon this wanting access to the request object within a generic view template you can do something like this in your urls.py:

from django.views.generic import ListView

class ReqListView(ListView):
    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        c = super(ReqListView, self).get_context_data(**kwargs)
        # add the request to the context
        c.update({ 'request': self.request })
        return c

url(r'^yourpage/$',
    ReqListView.as_view(
        # your options
    )
)

Cheers!

mVChr
  • 49,587
  • 11
  • 107
  • 104
1

What works for me was to add:

TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
                           "django.core.context_processors.request",
                           )

To the the settings.py not to the urls.py

Tonatiuh
  • 2,205
  • 1
  • 21
  • 22