如何从模型中获取一个项目并将相同的项目保存在另一个模型中的表单 django

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

我有一个电子商务网站,我有两个模型,一个名称是项目,另一个添加到购物车我想用它的 ID 获取模型,并想在另一个模型中获取相同的项目,所以我该怎么做我试过了

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

第二个模型

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

知道我想要的是从项目模型中获取该项目 ID 并将其保存在该用户的添加到购物车模型中 我如何获取该项目的 ID 我的 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>

现在正在徘徊如何保存在那个 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)

知道为什么我无法在我的 addtocart 模型中保存该项目模型的项目谢谢

您可以先获取 Item Instance,然后将其保存到您的 Addtocart 模型中。 我已经提到了两种处理方法。

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
                    )

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
                    )

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

只需稍微更改您的实际代码,执行以下操作:

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)

我不得不提一下,在 Django 中管理表单的最佳方法是使用 Forms 它会自动管理这些东西。看看那个。