Mark
Mark

Reputation: 2542

Django Generic View - Access to request

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')),
)

Upvotes: 7

Views: 6795

Answers (4)

Vishal Saha
Vishal Saha

Reputation: 56

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...

Upvotes: 3

Mark
Mark

Reputation: 2542

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!

Upvotes: 9

mVChr
mVChr

Reputation: 50187

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!

Upvotes: 3

Tonatiuh
Tonatiuh

Reputation: 2475

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

Upvotes: 1

Related Questions