Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')),
)
like image 538
Mark Avatar asked Aug 31 '10 08:08

Mark


People also ask

How generic views are used in Django?

Django's generic views were developed to ease that pain. They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to write too much code.

Why do we need generic views in Django and where is the best use case?

The generic class-based-views was introduced to address the common use cases in a Web application, such as creating new objects, form handling, list views, pagination, archive views and so on. They come in the Django core, and you can implement them from the module django.

How do I add a context to a class-based view in Django?

There are two ways to do it – one involves get_context_data, the other is by modifying the extra_context variable. Let see how to use both the methods one by one. Explanation: Illustration of How to use get_context_data method and extra_context variable to pass context into your templates using an example.

What is CBV in Django?

A view is a callable which takes a request and returns a response. This can be more than just a function, and Django provides an example of some classes which can be used as views. These allow you to structure your views and reuse code by harnessing inheritance and mixins.


2 Answers

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!

like image 116
Mark Avatar answered Oct 05 '22 22:10

Mark


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!

like image 24
mVChr Avatar answered Oct 05 '22 23:10

mVChr