Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Accessing HttpRequest in Class Based Generic View ListView

I'll be implementing a customized class based generic view by sub-classing ListView in my views.py. My question is how will be able to access the request (HttpRequest object) parameter in my sub-class? The HttpRequest object that I am pertaining to is the default request parameter for all functions inside views.py. Example:

def search(request):

To be clearer, here's what I've tried so far:

**views.py

class CustomListView(ListView):
    temp = ""

    def get(self, request, *args, **kwargs):
        self.temp = request.GET.get('temp')
        return super(CustomListView, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(CustomListView, self).get_context_data(**kwargs)
        context['temp'] = self.temp
        return context

**urls.py

url(r'^temp/$, CustomListView.as_view(queryset=Document.objects.all()[:1],template_name="temp.html")),

**temp.html

{% extends 'base.html' %}
{% block content %}
<h2>{{ temp }}
{% endblock %}

But all I am seeing when I run the server and access /temp/ (temp.html) is 'None'. So meaning, 'temp' is "" or 'temp' was not created at all.

Any ideas are greatly appreciated. Thanks!

like image 908
jaysonpryde Avatar asked Mar 19 '23 17:03

jaysonpryde


1 Answers

In general, you can use self.request in CBV methods that haven't been passed a request.

So you can use

    context['temp'] = self.request.GET.get('temp') 

in your get_context_data method, and then delete your get override method entirely.

like image 100
Steven Avatar answered Mar 21 '23 06:03

Steven