首页 > 解决方案 > 无法在电子商务应用程序-django 中获取产品 ID

问题描述

视图.py

    from django.shortcuts import render,redirect
    from .models import Cart
    from new_app.models import Product
    def cart_home(request):
                        
        cart_obj,new_obj=Cart.objects.new_or_get(request)
        products=Cart.objects.all()
        return render(request,'carts/home.html',{})
                    
                    
    def cart_update(request):
        print(request.POST)
        product_id=1
        print('id below')
        print(product_id) // not able to get the value of product id in console
        product_obj=Product.objects.get(id=product_id)
        cart_obj,new_obj=Cart.objects.new_or_get(request)
        if product_obj in cart_obj.products.all():
              cart_obj.products.remove(product_obj)
        else:
              cart_obj.products.add(product_obj)
        return redirect('home')

models.py(购物车)


    from django.db import models
    from django.conf import settings
    from new_app.models import Product
    from django.db.models.signals import pre_save,post_save,m2m_changed
    
    
    
    User=settings.AUTH_USER_MODEL
    
    class CartManager(models.Manager):
        def new_or_get(self,request):
            cart_id=request.session.get("cart_id",None)
            # qs=self.get_queryset().filter(id=cart_id)
            qs=self.get_queryset().only('products')
    
            print(qs)
            if qs.count()==1:
                    new_obj=False
                    cart_obj=qs.first()
                    print('cart obj below')
                    print(cart_obj)
                    if request.user.is_authenticated and cart_obj.user is None:
    
                        cart_obj.user=request.user
                        cart_obj.save()
    
    
            else:
                    cart_obj=Cart.objects.new_cart(user=request.user)
                    new_obj=True
                    request.session['cart_id']=cart_obj.id
            return cart_obj,new_obj
    
        def new_cart(self,user=None):
            user_obj=None
            if user is not None:
                if user.is_authenticated:
                    user_obj=user
            return self.model.objects.create(user=user_obj)
    
    class Cart(models.Model):
        user=models.ForeignKey(User,null=True,blank=True,on_delete=models.CASCADE)
        products=models.ManyToManyField(Product,blank=True)
        subtotal=models.DecimalField(default=0.00,max_digits=100,decimal_places=2)
    
        total=models.DecimalField(default=0.00,max_digits=100,decimal_places=2)
        timestamp=models.DateTimeField(auto_now_add=True)
        updated=models.DateTimeField(auto_now=True)
    
        objects=CartManager()
    
        def __str__(self):
            return str(self.id)
    
    
    def m2m_changed_cart_receiver(sender,instance,action,*args,**kwargs):
        print(action)
        if action=='post_add' or action=='post_remove' or action=='clear':
            products=instance.products.all()
            total=0
            for x in products:
                total += x.price
            if instance.subtotal != total:
                instance.subtotal=total
                instance.save()
    m2m_changed.connect(m2m_changed_cart_receiver,sender=Cart.products.through)
    
    
    def pre_save_cart_receiver(sender,instance,*args,**kwargs):
        if instance.subtotal>0:
            instance.total=instance.subtotal + 10
        else:
            instance.total=0.00
    
    pre_save.connect(pre_save_cart_receiver,sender=Cart)

update_cart.html

    <form method='POST' action='{% url 'update' %}' class="form ">{% csrf_token %}
      <input type="hidden"  name='product_id' value= "{{ product_id }}">
      {% if product in cart.products.all %}
        <button type="submit" class="btn btn-link">remove</button>
      {% else %}
        <button type="submit" class="btn btn-success">add to cart</button>
      {% endif %}
      </form>

终端输出:

    <QueryDict: {'csrfmiddlewaretoken': ['FMk2gTq6XXxZ2HU40I6h4b3WtPl59Drf1urwUNufDZUeSFPMzGNwU4L1QuGCiCbB'], 'product_id':
     ['']}>     -------- GETTING EMPTY DICTIONARY  INSTEAD OF GETTING PRODUCT ID i.e. 1
    id below
    1
    <QuerySet [<Cart: 13>]>

所以,除了csrf之外,我无法在那里获取产品ID ....我尝试单独打印产品ID ..它作为1 ...(写在输出中的“下面的ID”下)

  1. 我在处理电子商务网站的 CART 组件时遇到错误。问题在于 product_id(与 PRODUCT 模型具有外键关系)没有从 views.py 文件(在购物车中)获取。我已经导入了 PRODUCT 模型。但是,当我尝试打印 product_id 时,我得到了一个空字典。
  2. 如您所见,我已经复制了终端的输出,即 csrf token ,有一个 product_id 字典,它是空的。那里没有显示任何值。3.如果我从 PRODUCT 应用程序的 views.py 打印产品 ID,则会打印它。4.产品正在添加到购物车中,正如我在管理员中检查的那样。

标签: pythondjangomany-to-manye-commerce

解决方案


您是否检查了产品 ID 是否存在于生成的 HTML 中隐藏输入的值中?

如果不是这种情况,并且由于我看到您正在使用一个product对象,那么您可能应该在模板中使用{{ product.id }}而不是{{ product_id }}在第二行中使用它<input type="hidden" name='product_id' value= "{{ product_id }}">


推荐阅读