Ironman
Ironman

Reputation: 185

Increment view count in Django DetailView

I'm working on creating my own little auction style app similar to eBay, and I am simply trying to increment the viewCount variable I have set, and display that value as the number of times the page has been viewed.

In the views.py file, since I have a reference to my model, I thought I could invoke the incrementViewCount() in the model.py in this way:

views.py

class AuctionItemDetailView(DetailView):
    model = AuctionItem
    model.incrementViewCount()

model.py

viewCount = models.IntegerField(default=0)

def incrementViewCount(self):
    self.viewCount += 1
    self.save()

The error message in the console is as follows:

TypeError: incrementViewCount() missing 1 required positional argument: 'self'

I'd appreciate your guidance. Thanks.

Upvotes: 1

Views: 1001

Answers (2)

giofronza
giofronza

Reputation: 1

Make incrementation directly in the views.py.

class AuctionItemDetailView(DetailView):
    model = AuctionItem

    def get_object(self, queryset=None):
        item = super().get_object(queryset)
        item.viewCount += 1
        item.save()
        return item

Upvotes: 0

maciek
maciek

Reputation: 3354

You should override your view class get_object() method to increment the counter:

class AuctionItemDetailView(DetailView):
    model = AuctionItem

    def get_object(self, queryset=None):
        item = super().get_object(queryset)
        item.incrementViewCount()
        return item

Upvotes: 3

Related Questions