Home > Enterprise >  Django DetailView count increases by 3 instead of 1
Django DetailView count increases by 3 instead of 1

Time:06-03

I have a webpage where every view is being counted by and incremented by 3 where it is intended to be incremented by 1 instead

here's what I have in my views.py

from django.views.generic import ListView, DetailView
class MovieDetail(DetailView):
    model = Movie

    def get_object(self):
        object = super(MovieDetail, self).get_object()
        object.views_count  = 1
        object.save()
        return object

    def get_context_data(self, **kwargs):
        context = super(MovieDetail, self).get_context_data(**kwargs)
        context['links'] = MovieLink.objects.filter(movie=self.get_object())
        context['related_movies'] = Movie.objects.filter(category=self.get_object().category)
        return context

html

<section >
                    <img src="{{object.image.url}}">
                    <ul>
                        <li>{{object}}</li>
                        <li>{{object.description}}</li>
                        <li><a href="genre.html">Adventure</a>, <a href="genre.html">Drama</a>, <a href="genre.html">Romance</a></li>
                        <li><a href="">{{object.cast}}</a></li>
                        <li><i  id="eye"></i> {{object.views_count}}</li>
                    </ul>
                </section>

It is planned to increment by 1 but does not follow that logic.. what went wrong here?

CodePudding user response:

get_object() might get called more than once when your view is processed. You could for example move the code to the render_to_response() method. Also make sure to increment database fields using F() expressions.

from django.db.models import F


class MovieDetail(DetailView):
    model = Movie

    def render_to_response(self, *args, **kwargs):
        self.object.views_count = F('views_count')   1
        self.object.save()
        return super().render_to_response(*args, **kwargs)
  • Related