Django Generic View - Access to request
Asked Answered
P

4

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')),
)
Porphyroid answered 31/8, 2010 at 8:25 Comment(0)
P
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!

Porphyroid answered 31/8, 2010 at 8:41 Comment(2)
Not strictly true - it will be passed to all templates that are rendered using a RequestContext, which all generic views are.Aitchbone
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 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: #9899613Buddha
Z
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!

Zeuxis answered 2/2, 2012 at 2:33 Comment(0)
C
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...

Cristoforo answered 2/7, 2014 at 9:1 Comment(2)
great! This is very bad documented in Django. I exactly need the request obj. in the Listview subclass.Embarrassment
Link is dead, but it's here on web.archive.org: web.archive.org/web/20160923030156/http://www.gregaker.net/2012/…Crabbe
W
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

Wendelin answered 23/1, 2012 at 22:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.