Ironman
Ironman

Reputation: 185

Hit Count/Page View Functionality Django App

The question has been asked, and most suggest using django-hitcount. https://pypi.org/project/django-hitcount/

I tried that solution. But that solution is for python 2 use. Not python 3 use. Trying that solution I ran into the error described in this post: Django Hit Count ImportError

So I am trying to create this functionality. I have an auction item model. I am persisting viewCount among other fields:

models.py

from django.db import models
from django.contrib.auth.models import User
from PIL import Image
from django.utils import timezone

class AuctionItem(models.Model):

    seller = models.ForeignKey(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='auction_items')
    title = models.CharField(max_length=100)
    description = models.TextField()

    startBid = models.FloatField()
    buyNowPrice = models.FloatField()
    buyNowEnabled = models.BooleanField()
    deliveryCost = models.FloatField()

    startDate = models.DateTimeField(default=timezone.now)
    endDate =  models.DateTimeField(default=timezone.now)

    viewCount=models.IntegerField(default=0)

    def __str__(self):
        return self.title

    def save(self):
        super().save()

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

    def getCurrentTopBid():
        return startBid

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

I have a class based view class AuctionItemDetailView(DetailView) for the auction item detail view, and in it I am trying to increment the viewCount in the model by calling incrementViewCount()

views.py

from django.shortcuts import render, get_object_or_404
from django.contrib.auth.mixins import (
    LoginRequiredMixin, 
    UserPassesTestMixin
)
from django.contrib.auth.models import User
from django.views.generic import (
        ListView, 
        DetailView, 
        CreateView,
        UpdateView,
        DeleteView,

        )

from .models import AuctionItem

class AuctionItemListView(ListView):
    model = AuctionItem               #looks dir of app name   #template  #view
    template_name = 'auctionitem/auctionitem_list.html' #<app>/<model>_<viewtype>.html
    context_object_name = 'auctionitems'
    ordering = ['-startDate']
    paginate_by = 2

class UserAuctionItemListView(ListView):
    model = AuctionItem                #looks dir of app name   #template  #view
    template_name = 'auctionitem/user_auctionitems.html' #<app>/<model>_<viewtype>.html
    context_object_name = 'auctionitems'
    ordering = ['-date_posted']
    paginate_by = 2

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return AuctionItem.objects.filter(seller=user).order_by('-startDate')

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

class AuctionItemCreateView(LoginRequiredMixin, CreateView):
    model = AuctionItem
    fields = ['image', 'title', 'description', 'startBid', 'buyNowPrice', 'buyNowEnabled', 'startDate', 'endDate', 'deliveryCost', 'seller']
    success_url ='/'
    def form_valid(self,form):
        form.instance.seller = self.request.user
        return super().form_valid(form)

class AuctionItemUpdateView(LoginRequiredMixin,UpdateView):
    model = AuctionItem
    fields = ['title', 'description', 'startBid', 'buyNowPrice', 'buyNowEnabled', 'startDate', 'deliveryCost', 'seller']


    def form_valid(self,form):
        form.instance.seller = self.request.user
        return super().form_valid(form)

        def test_func(self):
            post = self.get_object()
            if self.request.user == auctionitem.seller:
                return True
            return False

class AuctionItemDeleteView(LoginRequiredMixin,UserPassesTestMixin, DeleteView):
    model = AuctionItem
    success_url ='/'

    def test_func(self):
            post = self.get_object()
            if self.request.user == auctionitem.seller:
                return True
            return False

But when I run the server I get the following error:

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

I tried passing 'self', and got the following error:

NameError: name 'self' is not defined

How can I make this work? Thanks, Ironman

Upvotes: 0

Views: 565

Answers (1)

Chris
Chris

Reputation: 2212

In your AuctionItemDetailView

def get(self, request, *args, **kwargs):
    res = super().get(request, *args, **kwargs)    
    self.object.incrementViewCount()
    return res

Upvotes: 1

Related Questions