首页 > 解决方案 > django 上的监视列表系统

问题描述

我想知道如何在 django 上创建一个 whatchlist,它也可以像一个选择喜欢的对象的功能。

这是我到目前为止的代码

模型.py

class Watchlist(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
    object = models.ForeignKey(Object, on_delete=models.CASCADE)

视图.py

def watchlist(request):
    return render(request, "auctions/watchlist.html", {
        "watchlists": Watchlist.objects.all()
    })

我还没有开始html

我的想法是,如果用户的关注列表中没有拍卖列表,则放置一个添加按钮,如果关注列表中有对象,则放置一个删除按钮。谁能帮我完成它,谢谢。

标签: pythondjango

解决方案


模型.py

class User(AbstractUser):
    pass

class Product(models.Model):
    title=models.CharField(max_length=50)
    desc=models.TextField()
    initial_amt=models.IntegerField()
    image=models.ImageField(upload_to='product')
    category=models.CharField(max_length = 20, choices =CHOICES)
    def __str__(self):
        return f"Item ID: {self.id} | Title: {self.title}"

class Watchlist(models.Model):
   user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
   item = models.ManyToManyField(Product)
   def __str__(self):
       return f"{self.user}'s WatchList"

在这里,产品和监视列表通过多对多字段链接,因为产品可以出现在多个用户的监视列表中,并且用户可以在监视列表中拥有多个项目。

视图.py

在关注列表中添加产品

def watchlist_add(request, product_id):
    item_to_save = get_object_or_404(Product, pk=product_id)
    # Check if the item already exists in that user watchlist
    if Watchlist.objects.filter(user=request.user, item=item_id).exists():
        messages.add_message(request, messages.ERROR, "You already have it in your watchlist.")
        return HttpResponseRedirect(reverse("auctions:index"))
    # Get the user watchlist or create it if it doesn't exists
    user_list, created = Watchlist.objects.get_or_create(user=request.user)
    # Add the item through the ManyToManyField (Watchlist => item)
    user_list.item.add(item_to_save)
    messages.add_message(request, messages.SUCCESS, "Successfully added to your watchlist")
    return render(request, "auctions/watchlist.html")

按钮可以这样添加:

<a href="{% url 'watchlist_add' product.id %}" role="button" class="btn btn-outline-success btn-lg">Add to Watchlist</a>

推荐阅读