Reputation:
I follow a tutorial in youtube just to add a like button to my Blog application, but the number of likes is not increasing in the template. but its increase when I highlight a user and hit save in the admin area. I mean its working fine in the admin but not in template.
How can I set that ?
the model:
class Photo(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.CharField(max_length=30,null=True, blank=False)
image = models.ImageField(null=False, blank=False)
description = models.TextField(null=True)
date_added = models.DateTimeField(auto_now_add=True)
likes = models.ManyToManyField(User, related_name='blog_posts')
def total_likes(self):
return self.likes.count()
def __str__(self):
return str(self.category)
the view:
def like(request, pk):
post = get_object_or_404(Photo, id=request.GET.get('post_id'))
post.Likes.add(request.user)
return HttpResponseRedirect(reverse('view', args=[str(pk)]))
def viewPhoto(request, pk):
post = get_object_or_404(Photo, id=pk)
photo = Photo.objects.get(id=pk)
stuff = get_object_or_404(Photo, id=pk)
total_likes = stuff.total_likes()
return render(request, 'photo.html', {'photo': photo, 'post': post, 'total_likes':
total_likes})
the templates:
<form action="{% url 'Photo' photo.id %}" method="POST">
{% csrf_token %}
{{ total_likes }}
<button type="submit", name="post_id" value="{{ post.id }}">Touch</button>
</form>
the urls:
path('', views.login, name='login'),
path('home', views.home, name='home'),
path('view/<str:pk>/', views.viewPhoto, name='Photo'),
path('post/create', views.PostCreativeView.as_view(), name='post_create'),
path('register', views.register, name='register'),
path('comment/<str:pk>/', views.comment, name='comment'),
path('like/<str:pk>/', views.like, name='like_post'),
Upvotes: 0
Views: 92
Reputation: 1001
Well it's very simple to get the number of liked objects in your form by simple doing something like this :
# In your view add s to the post variable
def viewPhoto(request, pk):
posts = get_object_or_404(Photo, id=pk)
photo = Photo.objects.get(id=pk)
stuff = get_object_or_404(Photo, id=pk)
total_likes = stuff.total_likes()
return render(request, 'photo.html', {'photo': photo, 'posts': posts, 'total_likes':
total_likes})
{% for post in posts %}
<form action="{% url 'like_post' photo.id %}" method="POST">
{% csrf_token %}
{{ post.likes.count }} # this would count and give you the total number of likes
<button type="submit", name="post_id" value="{{ post.id }}">Touch</button>
</form>
{% endfor %}
# OR
{% for post in posts %}
<form action="{% url 'like_post' photo.id %}" method="POST">
{% csrf_token %}
{{ total_likes }} # this would count and give you the total number of likes
<button type="submit", name="post_id" value="{{ post.id }}">Touch</button>
</form>
{% endfor %}
Upvotes: 0