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')),
)
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.
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.
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.
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.
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!
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With