3

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>

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.

Laba Ningombam
  • 105
  • 1
  • 2
  • 7

2 Answers2

1

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

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)
Ajmal Aamir
  • 1,085
  • 8
  • 8
0

You need to create a new view to add the product to the ShoppingList.

and link it using URL

Example:

Template

<a href="{% url 'app:add_product' product.pk %}">ADD</a>

urls.py

path("cart/add-product/<int:pk>/", ProductAddView.as_view(), name="add_product"),
Vignesh Krishnan
  • 743
  • 8
  • 15