Django上的监视列表系统 [英] Watchlist system on django
问题描述
我想知道如何在django上创建一个whatchlist,这就像选择一个喜欢的对象的函数一样.
I want to know how to create a whatchlist on django, it could be like a function to select favourite objects as well.
这是我到目前为止的代码
This is the code I've so far
models.py
models.py
class Watchlist(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
object = models.ForeignKey(Object, on_delete=models.CASCADE)
views.py
def watchlist(request):
return render(request, "auctions/watchlist.html", {
"watchlists": Watchlist.objects.all()
})
我还没有启动html
I didn't start html yet
我的想法是,如果用户的监视列表中没有拍卖清单,则在其中添加一个添加按钮,如果该监视列表中具有对象,则在其中放置一个删除按钮.谁能帮我完成它,谢谢.
My idea it's to put an add button where if the user doesn't have the auction listing on his watchlist, and a remove button if it has the object on the watchlist. could anyone help me to finish it, thanks.
推荐答案
models.py
models.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"
由于产品可以出现在多个用户的监视列表中,并且一个用户可以在监视列表中包含多个项目,因此产品和监视列表在许多领域之间具有很多联系.
Here the products and watchlist are linked by many to many field since a product can be present in multiple user's watchlists and a user can have multiple items in the watchlist.
views.py
将产品添加到监视列表中
adding the product in the watchlist
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>
这篇关于Django上的监视列表系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!