Good evening, everyone, Iām a beginner at Django I have blog page details that has count views and category for the blog post and blog post tags and other staff
my post model is:
class Post(models.Model):
title = models.CharField(max_length=250)
content = RichTextUploadingField()
post_date = models.DateTimeField(auto_now=True)
slug = models.SlugField(max_length=200, unique=True)
image = models.ImageField(null=True, blank=True, upload_to="images/")
tagss = models.ManyToManyField(Tags, blank=True, related_name='post')
Categorys = models.ManyToManyField(Category, blank=True, related_name='post')
views_count = models.IntegerField(default=0, null=True, blank=True)
def __str__(self):
return self.title
and my view is:
def post_page(request, slug):
post = Post.objects.get(slug = slug)
post.views_count = post.views_count + 1
post.save()
print("views:", post.views_count )
cats = Category.objects.all()
tags = Tags.objects.all()
# change 2 to how many random items you want
random_items = list(Post.objects.all().order_by('?')[:2])
related_posts = list(
Post.objects.filter(
Q(tagss__name__in=[tag.name for tag in post.tagss.all()]) |
Q(Categorys__name__in=[Category.name for Category in post.Categorys.all()])
).distinct()
)
recent_posts = Post.objects.all().order_by('-id')[:4]
context = {'post': post, 'cats': cats, 'tags': tags, 'recent_posts': recent_posts,
'random_blog': random_items, 'related_posts': related_posts}
return render(request, 'blog/Blog_details.html', context)
my problem is when I refresh the post page the views increase by 2 I need when the user refresh the page to increase by 1
Thanks, everyone