如何使用django更新购物车项目数量?

时间:2019-06-07 07:24:23

标签: django django-models django-forms django-templates django-views

希望有人会帮助我解决我的问题。 从前一段时间以来,我遇到了我的代码问题,即使我似乎一切都很好,我也不明白为什么它不起作用。我想提供更新购物车数量的可能性,但是我只能从管理员那边来做,而不能从带有表单的过帐请求中完成。

我已经尝试了很多在互联网上找到的示例,但是似乎没有什么可以解决我的问题。当我发布数量时,我可以通过执行print(request.POST)来查看从终端发布的数据,但是并不需要管理员更新购物车数量。

要保存的信号:

def m2m_changed_cart_receiver(sender, instance, action, *args, **kwargs):
print("hello depuis le model")
if action == 'post_add' or action == 'post_remove' or action == 'post_clear':
    bustravels = instance.bustravels.all()
    #busquantity = BusCart.objects.get(booking_seats_num=1)
    total = 0
    for x in bustravels:
        total += x.price
    if instance.subtotal != total:
        instance.subtotal = total
        instance.save()

  m2m_changed.connect(m2m_changed_cart_receiver, sender=BusCart.bustravels.through)

def pre_save_cart_receiver(sender, instance, *args, **kwargs):
if instance.subtotal > 0:
    instance.total = Decimal(instance.subtotal) * Decimal(1.015) # 1.5% tax
else:
    instance.total = 0.00

pre_save.connect(pre_save_cart_receiver, sender=BusCart)

这是我的模特代码:

class Entry(models.Model):
bustravels = models.ForeignKey(BusTravels, null=True,   on_delete='CASCADE')
bus_cart = models.ForeignKey(BusCart, null=True, on_delete='CASCADE')
booking_seats_num = models.PositiveIntegerField(default=1, blank=True, null=True)

def __str__(self):
    return "This entry contains {} {}(s).".format(self.booking_seats_num, self.bustravels)

@receiver(post_save, sender=Entry)
def update_cart(sender, instance, **kwargs):
  item = instance.booking_seats_num * instance.bustravels.price
  instance.bus_cart.subtotal += item
  instance.bus_cart.booking_seats_num += instance.booking_seats_num
  instance.bus_cart.updated = datetime.now()

购物车模型:

class BusCart(models.Model):
user                = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
bustravels          = models.ManyToManyField(BusTravels, blank=True)
booking_seats_num   = models.PositiveIntegerField(default=1)
subtotal            = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
total               = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
updated             = models.DateTimeField(auto_now=True)
timestamp           = models.DateTimeField(auto_now_add=True)

objects = BusCartManager()

ModelManager:

class BusCartManager(models.Manager):
def bus_new_or_get(self, request):
    bus_cart_id = request.session.get('bus_cart_id', None)
    qs = self.get_queryset().filter(id=bus_cart_id)
    if qs.count() == 1: 
        bus_new_obj = False
        bus_cart_obj = qs.first()
        if request.user.is_authenticated and bus_cart_obj.user is None:
            bus_cart_obj.user = request.user
            bus_cart_obj.save()
        #print("Cart id exists")
    else:
        bus_cart_obj = BusCart.objects.bus_new_cart(user=request.user)
        bus_new_obj = True
        request.session['bus_cart_id'] = bus_cart_obj.id
    return bus_cart_obj, bus_new_obj

def bus_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)

我的modelForm用来发布数据:

class BusQuantityForm(forms.ModelForm):
PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 71)]
booking_seats_num = forms.TypedChoiceField(label='Number of places', choices=PRODUCT_QUANTITY_CHOICES, coerce=int, required=False)

class Meta:
    model = Entry
    fields = ['booking_seats_num',] #'bustravels', 'bus_cart', ]

这是我的观点:

form = BusQuantityForm(request.POST, request.FILES or None)
# if request.method == 'POST':

if form.is_valid():
    print(request.POST)
    bus_travels_id = request.POST.get('bus_travels_id')
    booking_seats_num = request.POST.get('booking_seats_num')
    if bus_travels_id is not None:
        bus_cart_obj, bus_new_obj = BusCart.objects.bus_new_or_get(request)
        bus_travels_obj = BusTravels.objects.get(id=bus_travels_id)
        #Entry.objects.create(bus_cart=bus_cart_obj, bustravels=bus_travels_obj, booking_seats_num=booking_seats_num)
        # bus_cart_obj.bustravels.add(bus_travels_obj) # bus_cart_obj.bustravels.add(bus_travels_id)
        # added = True
        # bus_travels_id = request.POST.get('bus_travels_id')
        instance = form.save(commit=False)
        instance.booking_seats_num = booking_seats_num
        instance.bustravels = bus_travels_obj
        instance.bus_cart = bus_cart_obj
        instance.save()

我的模板是:

<td>
    <form action="{% url 'bus_cart_home' %}" method="POST">
     {% csrf_token %}  <input type="hidden" name="bustravels" value="{{ product }}" readonly>
   <input type="hidden" name="bus_cart" value="{{ bus_cart }}" readonly>
    {{ form.booking_seats_num|as_crispy_field }}
    <input type="submit" value="Updated" class="btn btn-info" style="background-color: #0c1836;">
   </form>
 </td>

正如我所说的,在我来这里寻求帮助之前,我已经尝试了多种方法来解决此问题,我尝试了很多方法,但是我仍然没有想要更新购物车数量的东西。

任何帮助将不胜感激。

提前谢谢您。

0 个答案:

没有答案