如何使用Django在主页上为多个对象添加“喜欢”?

时间:2019-06-08 13:36:41

标签: python django django-views

我有一个适用于产品详细信息页面的Ajax赞/不喜欢按钮。但是,我想将其添加到列出了多个产品的主页上。这是我目前在 models.py 中所拥有的:

class Product(models.Model):
    ...
    likes = models.ManyToManyField(User, blank=True, related_name='likes')
    ...

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


    def is_liked(self, request):
        return self.likes.filter(id=request.user.id).exists()

views.py

def home(request):
    products = Product.objects.all().order_by('-pub_date')
    return render(request, 'product/home.html', {'product': products})


def detail(request, product_id):
    product = get_object_or_404(Product, product_id=product_id)
    is_liked = False
    if product.likes.filter(id=request.user.id).exists():
        is_liked = True
    context = {
        'product': product,
        'is_liked': is_liked,
        'total_likes': product.total_likes()
    }
    return render(request, 'product/detail.html', context)


def like_product(request):
    product = get_object_or_404(Product, id=request.POST.get('id'))
    if product.likes.filter(id=request.user.id).exists():
        product.likes.remove(request.user)
        is_liked = False
    else:
        product.likes.add(request.user)
        is_liked = True
    context = {
        'product': product,
        'is_liked': is_liked,
        'total_likes': product.total_likes()
    }
    if request.is_ajax():
        html = render_to_string('product/likes.html', context, request=request)
        return JsonResponse({'form': html})

home.html

<div class="album py-5 bg-dark">
  <div class="container">
    <div class="row">
      {% for product in product.all %}
      {% if product.featured %}
        ...
        <div id="like-section-{{ product.id }}">{{ product.total_likes }} Like{{ product.total_likes|pluralize }}
          <form action="{% url 'like_product' %}" method="post">{% csrf_token %}
            {% if product.is_liked %}
              <button type="submit" name="product_id" value="{{ product.id }}" class="btn btn-like btn-danger">Dislike</button>
            {% else %}
              <button type="submit" name="product_id" value="{{ product.id }}" class="btn btn-like btn-primary">Like</button>
            {% endif %}
          </form>
        </div>
        ...
      {% endif %}
      {% endfor %}
    </div>
  </div>
</div>

当前“赞/不喜欢”按钮的状态尚未保存(当我按“赞”时,按钮变为“不喜欢”,并记录了类似内容。但是,在我重新加载后,页面按钮又变为“赞”) 。似乎is_liked类中的Product函数中存在问题。不知道如何解决。非常感谢您的帮助!

0 个答案:

没有答案