python – 如何显示用户是否已经喜欢Django中的对象实例

我的Django模型中有下表,菜肴和喜欢.在我的主页上,我显示了数据库中所有菜肴的列表,每个菜上都有一个相似的按钮.对于用户喜欢的菜肴,我想表明他们已经喜欢它,以便它们可以不同于它,反之亦然.过去几天我一直在尝试不同的方法,但似乎无法解决任何问题.这是我最近尝试失败的代码.

#dishes table
class Dishes(models.Model):
    name = models.CharField(max_length=40, unique=True)

    def liked(dish, user):
        try:
            user_upvoted = Likes.objects.get(dish=dish, user=user)
        except:
            user_upvoted = None
        if user_upvoted:
            return True
        else:
            return False


#upvotes
class Likes(models.Model):
    dish = models.ForeignKey(Dishes)
    user = models.ForeignKey(User)
    date_added = models.DateTimeField(auto_now_add=True)

def home(request):
    this_user = auth.models.User.objects.get(id=1)

    dishes = models.Dishes.objects.all()
    for dish in dishes:
         models.Dishes.voted(dish, this_user)

    `enter code here`return render_to_response('frontend/home.html', { 'dishes': dishes, })

最佳答案 添加ManyToMany使这个问题变得容易解决:

class Dishes(models.Model):
    name = models.CharField(max_length=40, unique=True)
    likes = models.ManyToManyField(Likes)

class Likes(models.Model):
    dish = models.ForeignKey(Dishes)
    user = models.ForeignKey(User)
    date_added = models.DateTimeField(auto_now_add=True)

像这样调整你的视图:

from django.contrib.auth.decorators import login_required
from django.shortcuts import render

@login_required
def home(request):
    dishes = Dishes.objects.all()
    return_list = []
    for dish in dishes:
        return_list.append((dish, dish.likes_set.filter(user=request.user)))
    return render(request, 'dish_list.html', {'dishes': return_list})

您的模板是“切换”的地方:

 {% for dish, liked in dishes %}
     {{ dish.name }}
     {% if liked %}
          You already like this dish.
     {% else %}
          Like this dish now, its yummy!
     {% endif %}
  {% endfor %}

或者,如果您无法更改模型,请调整您的视图代码,如下所示:

@login_required
def home(request):
    dishes = Dishes.objects.all()
    return_list = []
    for dish in dishes:
        return_list.append((dish,
                            Likes.objects.filter(user=request.user, dish=dish)))
    return render(request, 'dish_list.html', {'dishes': return_list})

我们的想法是,已经为登录的用户标记了返回到模板的对象列表.

login_required decorator确保仅在用户登录时调用视图.否则,它将用户重定向到登录页面.

render shortcut将确保始终从您的视图传递RequestContext.

点赞