What I want to do is that an entry has a visit counter but I can not implement it correctly.
models.py
class Post(models.Model):
title = models.CharField(max_length=50)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
created_date = models.DateTimeField(auto_now_add=True)
views = models.PositiveIntegerField(default=0)
def __str__(self):
return self.title
def get_absolute_url(self):
return 'detail/%s' % self.pk
My problem is in get_context_data () I think, but I do not understand why ListView does not have the attributes of the model .
views.py
class PostListView(generic.ListView):
model = Post
context_object_name = 'posts'
template_name = 'home.html'
queryset = Post.objects.order_by('-created_date')
def get_context_data(self, **kwargs):
self.views += 1
self.save()
kwargs['views'] = self.views
return super().get_context_data(**kwargs)
class PostDetailView(generic.DetailView):
model = Post
context_object_name = “post”
template_name = ‘detail.html’
def get_context_data(self, **kwargs):
self.views += 1
self.save()
#Aqui realmente no se que retornar
I could make it work with function based views but it's not what I really want, I'd like to be able to do it with CBV.
This is what I want to achieve, but done in the generic class
def post_detail(request, post_pk):
post = Post.get_object_or_404(Post, pk=post_pk)
post.views += 1
post.save()
return render(request, ‘detail.html’, {‘post’: post }
Sorry if I give little information or the question is wrong, I'm relatively new.