喜欢匹配查询不存在 - Django

Like matching query does not exist - Django

我创建了一个点赞按钮,可以在用户喜欢照片时将其添加到查询中,如果他们不喜欢照片则将其删除。

后端工作得很好!前端,没那么多。

我尝试加载页面时出现以下错误:Like matching query does not exist.

问题出在这行代码中:like = Like.objects.get(pk=obj.id)

有人可以帮我在我的 html 文件中显示 {% if request.user.username in like.get_likers %}{{ like.likers.count }} 的正确代码吗?

非常感谢!

HTML:

{% if request.user.username in like.get_likers %}
    <input id="like_btn" name="{{ obj.slug }}" value="Liked" type="button" />
{% else %}
    <input id="like_btn" name="{{ obj.slug }}" value="Like" type="button" />
{% endif %}
<h3>
    <a href="{% url 'like_thread' %}"><strong id="like_count">{{ like.likers.count }}</strong></a>
</h3>

VIEWS.PY:

def photo_detail(request, photo_slug, username):
    u = MyUser.objects.get(username=username)
    obj = get_object_or_404(Photo, slug=photo_slug)
    like = Like.objects.get(pk=obj.id)

    context = {
        "like": like,
        "obj": obj
    }
    return render(request, "photos/photo_detail.html", context)

MODELS.PY:

class Photo(models.Model):
    creator = models.ForeignKey(MyUser, null=False)
    image = models.ImageField(upload_to='user/photos/', null=True, blank=True)
    slug = models.SlugField(null=False, blank=False)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)

class Like(models.Model):
    image = models.ForeignKey(Photo)
    likers = models.ManyToManyField(MyUser, related_name='Likers', null=True, blank=True)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    def __unicode__(self):
        return "CREATOR: %s | SLUG: %s" %(self.image.creator, self.image.slug)

    def get_likers(self):
        return ", ".join([a.username for a in self.likers.all()])

您需要检查是否有赞。在视图和模板中。由于 like 变量可能有内容也可能没有,您可以先在视图中检查。如果存在,则将其添加到字典中。

def photo_detail(request, photo_slug, username):
    u = MyUser.objects.get(username=username)
    obj = get_object_or_404(Photo, slug=photo_slug)

    context = {
        "obj": obj
    }
    # find out if there are any likes, if there are, add 
    # to the context dictionary
    try: 
        like = Like.objects.get(pk=obj.id)
        context['like'] = like
    except Like.DoesNotExist:
        pass

    return render(request, "photos/photo_detail.html", context)

然后在你的模板中,你还需要做一个if:

 {% if like %}
      <input id="like_btn" name="{{ obj.slug }}" value="{% if request.user.username in like.get_likers %}Liked{% else %}Like{% endif %}" type="button" />}
 {% endif %}

尽管如此,您也可以轻松地检查用户是否喜欢视图中的照片。