python - 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
我的想法是,如果用户的关注列表中没有拍卖列表,则放置一个添加按钮,如果关注列表中有对象,则放置一个删除按钮。谁能帮我完成它,谢谢。
解决方案
模型.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>
推荐阅读
- javascript - django使用ajax调用后端有问题
- android - 如何使用 Volley 发送 base 64 字符串
- ios - SwiftUI:主从视图中的 SafariView
- java - 为什么当我在eclipse中的spring boot项目中执行主类时出现这个错误“找不到或加载主类”
- templates - 根据某种状态从文档生成中过滤掉图表
- r - 删除数据表中的行 - 闪亮
- javascript - 如何在没有 global.css 文件的情况下覆盖 next.Js 中的材料 ui 类?
- google-analytics-4 - GA4 on Web 事件和渠道问题
- sql - Q 表示法不适用于 oracle 12c 中的变量
- javascript - 如何使文本对齐:在谷歌应用脚本(日历)中居中?