Reputation: 428
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.
Upvotes: 6
Views: 3115
Reputation: 61
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.
Upvotes: 3
Reputation: 476594
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)
Upvotes: 10