Django: How to implement request.session in a class based view
Asked Answered
E

2

6

I have a hard time understanding class based views in Django. At this time I try to implement a request.session in a ListView. I try to implement the following function based code from the MdM Django Tutorial in to a ListView.

def index(request):
    ...
    
    # Number of visits to this view, as counted in the session variable.
    num_visits = request.session.get('num_visits', 0)
    request.session['num_visits'] = num_visits + 1

    context = {
        'num_visits': num_visits,
    }
    
    return render(request, 'index.html', context=context)

I tried the following (and a lot of other things) but to no avail:

class ListPageView(FormMixin, ListView):
    template_name = 'property_list.html'
    model = Property
    form_class = PropertyForm

    def get(self, request, *args, **kwargs):
        num_visits = request.session.get('num_visits', 0)
        request.session['num_visits'] = num_visits + 1

        return super().get(request, *args, **kwargs)

    # ... some more code here

In my template I have:

<p>You have visited this page {{ num_visits }}{% if num_visits == 1 %} time{% else %} times{% endif %}.</p>

But the template variable renders always empty.

Essay answered 20/12, 2019 at 21:33 Comment(0)
G
10

You still need to pass it to the context, by overriding the get_context_data method [Django-doc]:

class ListPageView(FormMixin, ListView):
    template_name = 'property_list.html'
    model = Property
    form_class = PropertyForm

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['num_visits'] = self.request.session['num_visits']
        return context

    def get(self, request, *args, **kwargs):
        num_visits = request.session.get('num_visits', 0)
        request.session['num_visits'] = num_visits + 1
        return super().get(request, *args, **kwargs)
Gurrola answered 20/12, 2019 at 21:37 Comment(1)
I am attempting to save save data to a session variable in a class view on the above lines. However the session variable does get updated. Tried to check using print(request.session.items()) but nothing gets printed.Dichromatism
J
3

I understand that this is a late answer, but I ran into the same problem, and I will try to put my two cents in and maybe my answer will help newbies like me.

Your template always has access to the {{ request }} variable, so you can simply use {{request.session.key}} without defining additional context.

I can also see that you used the {% if %} conditional for the plural, but Django has a nice filter {{ value|pluralize }}, it might be more useful for that.

Judicature answered 5/8, 2021 at 13:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.