Search code examples
pythondjangoquerying

Django Query Error: How do i properly query my total likes to show in the Home Screen?


Can anyone advise on how to query the `total_likes of a post to be shown in my HTML, I tried, but was given this error:

Page not found (404)
No BlogPost matches the given query.

THANK YOU!

I think it might be the way I am querying and linking the blog post with the likes but I'm not sure why I'm wrong and I don't know how to modify it despite trying for a few hours.

views.py

def home_feed_view(request, **kwargs):
    
    context = {}

    blog_posts = sorted(BlogPost.objects.all(), key= attrgetter('date_updated'), reverse = True)
    blog_post = get_object_or_404(BlogPost, slug=request.POST.get('blog_post_slug'))
    total_likes = blog_post.total_likes()
    liked = False
    if blog_post.likes.filter(id=request.user.id).exists():
        liked = True
    context['blog_posts'] = blog_posts 
    context['blog_post'] = blog_post
    context['total_likes'] = total_likes
    return render(request, "HomeFeed/snippets/home.html", context)


def LikeView(request, slug):
    context = {}

    post = get_object_or_404(BlogPost, slug=slug)
    liked = False
    if post.likes.filter(id=request.user.id).exists():
        post.likes.remove(request.user)
        liked = False
    else:
        post.likes.add(request.user)
        liked = True 
    return redirect('HomeFeed:detail', slug=slug)

.html

{% for post in blog_posts %} 

<td class="table-primary">

  <form action="{% url 'HomeFeed:like_post' post.slug %}" method="POST">
    {% csrf_token %} 

    <button type="submit" name="blog_post_slug"  value="{{post.slug}}" class='btn btn-primary btn-sm'>
      Like
    </button> 

    {{ total_likes }} Likes

  </form>

</td>   

{% endfor %}

models.py

class BlogPost(models.Model):
    body = models.TextField(max_length=5000, null=False, blank=False)
    likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='blog_posts', blank=True)
    slug = models.SlugField(blank=True, unique=True)
 

    def total_likes(self):
        return self.likes.count()
  

urls.py

from django.urls import path
from HomeFeed.views import(
    home_feed_view,
    LikeView,
)

urlpatterns = [
    path('', home_feed_view , name= "main"),
    path('<slug>/like/', LikeView, name='like_post'),
]


Solution

  • The exception: Page not found (404) No BlogPost matches the given query. is being raised by get_object_or_404 as it does exactly what the name says. If the BlogPost with the supplied slug in any of the views doesn't exist in the database, Django will raise an Http404 exception as you're witnessing.

    Now, since we don't know the structure of your BlogPost model, I can't really tell you where to change, all I can tell you is you need to make sure, the slug is a unique field on each BlogPost instance, othwerwise your code is working as one would expect.

    EDIT

    I had not seen the BlogPost model, my bad, but the information is still relavant a BlogPost with such a slug does not exist. So do a manual check, see what the slug arrives in the view(s) as, and then check manually either in DB or in your shell.