0

i have an ecommerce site i have tow model one name is item and other add to cart i want to fetch the model with it it id and want to the same item in another model so how i can do that this what i tried

class Item(models.Model):
    auth = [
        ('✔','✔'),
        ('✖','✖')
    ]
    categories = models.ForeignKey(Categories, on_delete=models.CASCADE, related_name='our_items')
    subcategories = models.ForeignKey(Subcategories, on_delete=models.CASCADE, related_name='products')
    name = models.CharField(max_length=200, blank=False)
    contain_size = models.CharField(max_length=50, blank=True)
    brand_name = models.CharField(max_length=100, blank=False, default=None)
    swag = models.BooleanField(default=False)
    footwear = models.BooleanField(default=False)
    first = models.ImageField(upload_to='items', blank=False)
    second = models.ImageField(upload_to='items', blank=False)
    taken_from = models.CharField(max_length=1000)
    color = models.CharField(max_length=30, blank=True)
    material = models.CharField(max_length=50, blank=False)
    return_policy = models.CharField(max_length=100, blank=False, default='7Days Return Policy')
    stock = models.CharField(max_length=50, blank=False, default='In Stock')
    authentic = models.CharField(max_length=1,blank=False,choices=auth, default='✔')
    price = models.FloatField(blank=False,)
    actual_price = models.FloatField(blank=False)
    type = models.CharField(blank=True, max_length=100,)
    about = models.CharField(blank=True,max_length=100,)
    offer = models.CharField(max_length=4, blank=True)
    joined_date = models.DateTimeField(default=timezone.now,editable=False)
    update_at = models.DateTimeField(auto_now=True)
    description = models.TextField(blank=True)
    
    @staticmethod
    def get_items_by_id(ids):
        return Item.objects.filter(id__in = ids)

    def __str__(self):
        return self.name

second model

class Addtocart(models.Model):
    User = models.OneToOneField(User, on_delete=models.CASCADE)
    item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='cart_item')
    added_date = models.DateField(auto_now=True)


    def __str__(self):
        return self.user.username

know what i want is to take that item id from item model and save it in add to cart model for that user how i fetching id of that item my html

<form method="POST" action="#{{ item.id }}">
                  {% csrf_token %}
                  <input type="text" hidden value="{{item.id}}" name="item">
                  <button class="btn btn-outline-primary add" type="submit" style="float: left;">Add To Cart</button>
                </form>

now wandering how to save in that addtocartmodel

#updated view

class Product_detail(View):
    def get(self, request, item_id,):
        item = Item.objects.filter(id=item_id)
        category_list = Categories.objects.all()
        items = Item.objects.order_by('-update_at')
        return render (request, 'product_detail.html',{"items" : item, 'category_list': category_list, 'item': items })
    
    def post(self, request, item_id):
         item = request.POST.get('item')
         user = request.user
         cart = Addtocart.objects.create(
                    user=user,
                    item = item
                    )
         return redirect('products:detail', item_id=item_id)

any idea why i am unable to save that item of item model in my addtocart model thank you

3
  • Do you have any errors when you do the post action?
    – allexiusw
    Sep 26, 2021 at 16:21
  • @allexiusw Cannot assign "'1'": "Addtocart.item" must be a "Item" instance. Sep 26, 2021 at 17:35
  • Checkout the answer, you just need to change a little bit your code.
    – allexiusw
    Sep 26, 2021 at 19:48

2 Answers 2

1

Just have to change a little your actual code, do the following:

class Product_detail(View):
    def get(self, request, item_id,):
        item = Item.objects.filter(id=item_id)
        category_list = Categories.objects.all()
        items = Item.objects.order_by('-update_at')
        return render (request, 'product_detail.html',{"items" : item, 'category_list': category_list, 'item': items })
    
    def post(self, request, item_id):
         item = request.POST.get('item')
         # change it
         item_obj = Item.objects.get(pk=item)
         user = request.user
         cart = Addtocart.objects.create(
                    user=user,
                    # Change here
                    item = item_obj
                    )
         return redirect('products:detail', item_id=item_id)

I have to mention that the best approach to manage forms in Django is using Forms it manage this things automatically. Take a look of that.

1

You can first get the Item Instance and then save it to your Addtocart model. I have mentioned two ways you can handle this.

from django.shortcuts import get_object_or_404

item = request.POST.get('item')
item_instance = get_object_or_404(Item, id=item)
cart = Addtocart.objects.create(
                    user=user,
                    item = item_instance
                    )

or

item = request.POST.get('item')
item_instance = Item.objects.get(id=item)
# Might have to handle exception if we can't find the Item Instance
cart = Addtocart.objects.create(
                    user=user,
                    item = item_instance
                    )

or

item = request.POST.get('item')
cart = Addtocart.objects.create(user=user, item_id=item)
0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.