如何在Django中为产品实施“添加到愿望清单"? [英] How to implement Add to WishList for a Product in Django?
问题描述
我正在实现一个应用程序,用户可以在其中创建购物清单,并可以搜索产品并将该产品添加到购物清单中.
I am implementing an app in which a User can create a Shopping List and can search for a Product and add the Product to the Shopping List.
我被困在如何添加到列表"部分.我创建了模型,如下所示:
I am stuck at the 'how to add to the list' part. I have created the Model as follows:
class Product(models.Model):
pid = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100, db_index=True)
description = models.TextField(blank=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_detail', args=[self.pid, self.slug])
class ShoppingList(models.Model):
user = models.ForeignKey(User, related_name='shoplist', on_delete=models.CASCADE)
list_name = models.CharField(max_length=20)
items = models.ManyToManyField(Product)
slug = models.SlugField(max_length=150, db_index=True)
def __str__(self):
return self.list_name
def get_absolute_url(self):
return reverse('shop:item_list', args=[self.slug])
在用于查看每个产品的模板中,我有以下
In the Template to view each Product, I have the following
<h3>{{ product.name }}</h3>
<a href="(What is to be written here)">ADD</a>
我需要在单击添加按钮时将要通过get_absolute_url显示的特定产品添加到购物清单中.
I need the Particular product which I am displaying through the get_absolute_url, to be Added to the Shopping List, when the ADD button is cliked.
我不知道下一步该怎么做.请帮忙.
I am lost as to what Steps to take next. Please help.
推荐答案
首先,为您的愿望清单创建一个模型,如下所示:
At first create a model for your wishlist like below
class Wishlist(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)# here CASCADE is the behavior to adopt when the referenced object(because it is a foreign key) is deleted. it is not specific to django,this is an sql standard.
wished_item = models.ForeignKey(Item,on_delete=models.CASCADE)
slug = models.CharField(max_length=30,null=True,blank=True)
added_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.wished_item.title
然后创建一个用于将商品添加到愿望清单中的功能....我以这种方式使用了Tryid ...
then create a function for adding the item in the wishlist.... i have tryid this way...
@login_required
def add_to_wishlist(request,slug):
item = get_object_or_404(Item,slug=slug)
wished_item,created = Wishlist.objects.get_or_create(wished_item=item,
slug = item.slug,
user = request.user,
)
messages.info(request,'The item was added to your wishlist')
return redirect('core:product_detail',slug=slug)
这篇关于如何在Django中为产品实施“添加到愿望清单"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!