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.
print(request.session.items())
but nothing gets printed. – Dichromatism