Hello there, am trying to add a Liking functionality to my blog posts using only python without Ajax or the rest. I added a ‘likes’ attribute with a ManyToManyField to my Post model. here is the view function that concerns the Like feature
def LikeView(request, slug):
post = get_object_or_404(Post, id=request.POST.get('post_id'))
post.likes.add(request.user)
return HttpResponseRedirect(reverse('post_detail', args=[str(slug)]))
class PostDetailView(generic.DetailView):
model = Post
template_name = 'blog/post_detail.html'
def get_context_data(self, *args, **kwargs):
context = super(PostDetailView, self).get_context_data(**kwargs)
stuff = get_object_or_404(Post, id=self.kwargs['slug']) #here is the particular line that get called up
total_likes = stuff.total_likes()
context["total_likes"] = total_likes
return context
I replaced pk with slug because pk always throws errors whenever I used it. here is the url path;
path('like/<int:slug>/', views.LikeView, name='like_post'),
Here is the part of my post_details.html template that displays the like feature;
<div class="text-left">
<form action="{% url 'post_likes' post.slug %}" method="POST">
{% csrf_token %}
<button type="submit", name="post_id", value="{{ post.id }}", class="btn btn-primary btn-lg">
<span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span> Like
</button> - {{ total_likes }} Likes
</form>
</div>
but then when I click the Readmore link to the post-detail page, i get this error
ValueError at /blogpost-7/
Field 'id' expected a number but got 'blogpost-7'.
Request Method: GET
Request URL: http://127.0.0.1:8000/blogpost-7/
Django Version: 3.0.8
Exception Type: ValueError
Exception Value:
Field 'id' expected a number but got 'blogpost-7'.
Exception Location: C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\__init__.py in get_prep_value, line 1774
I can`t seem to fix this error