没有与给定查询匹配的关注列表

问题描述 投票:0回答:1

尝试将项目添加到我的关注列表时突然开始返回错误

没有与给定查询匹配的关注列表。

这是我的代码的样子。

模型.py

class Listing(models.Model):
    product_name = models.CharField(max_length=64, verbose_name="product_name")
    product_description = models.TextField(max_length=200, verbose_name="product description")
    product_image = models.ImageField(upload_to="images/", verbose_name="image", blank=True)
    is_active = models.BooleanField(blank=False, default=True)
    initial_price = models.DecimalField(decimal_places=2, max_digits=6, default=False)
    owner = models.ForeignKey(User, related_name="auction_owner", on_delete=models.CASCADE, default=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category")
    
    def __str__(self):
        return self.product_name

class Watchlist(models.Model):
    user = models.OneToOneField(User, on_delete=models.DO_NOTHING)
    items = models.ManyToManyField(Listing, null=True, related_name="watchlist_item")

views.py

def add_to_watchlist(request, item_id):
item = get_object_or_404(Listing, pk=item_id)
user_watchlist = get_object_or_404(Watchlist, user=request.user)
user_watchlist.items.add(item)
return redirect("watchlist")

urls.py

path("add_to_watchlist/<int:item_id>", views.add_to_watchlist, name="add_to_watchlist"),

模板

<div class="btn-groups">
      {% if listing in watchlist_items %}
      <a href="{% url 'remove_from_watchlist' item_id=listing.id %}" class="fas fa-shopping-cart"><button type = "button" class = "add-cart-btn">remove from watchlist</button></a>
      {% else %}
      <a href="{% url 'add_to_watchlist' item_id=listing.id %}" class="fas fa-shopping-cart"><button type = "button" class = "add-cart-btn">add to watchlist</button></a>
      {% endif %}
</div>
django django-models django-views django-templates
1个回答
0
投票

这是因为对于该用户,尚未添加

Watchlist
,如果缺少,您可以使用以下命令创建一个: def add_to_watchlist(request, item_id): item = get_object_or_404(Listing, pk=item_id) user_watchlist, __ = Watchlist.objects.get_or_create(user=request.user) user_watchlist.items.add(item) return redirect('watchlist')



注意

HTTP 协议第 9 节 指定像 GET 和 HEAD 这样的请求不应该有副作用,所以你 不应根据此类请求更改实体。通常 POST、PUT、PATCH 和 DELETE 请求用于此目的。在这种情况下,您可以制作一个小<form>, 会触发 POST 请求,或者您使用一些 AJAX 调用。有些浏览器会寻找 链接并已彻底缓存此类链接的响应,因此这些可能 触发此类视图会产生副作用。

© www.soinside.com 2019 - 2024. All rights reserved.