Home > Net >  how to fetch a item from model and save the same item in another model with form django
how to fetch a item from model and save the same item in another model with form django

Time:09-27

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

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

CodePudding user response:

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)

CodePudding user response:

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.

  • Related