如何从ModelForm获取值

时间:2019-05-04 05:27:38

标签: python django

如何在ModelForm中显示捕获的数据,在本示例中为数量,如何在模板中显示数据以及如何在数据库中获取数据

models.py

class OrderItem(models.Model):

    PRODUCT_QUANTITY_CHOICES = (
        (1, 1), (2, 2), (3, 3), (4, 4)
    )

    quantity = models.IntegerField(default=2, choices=PRODUCT_QUANTITY_CHOICES)
    order_no = models.IntegerField(primary_key=True, )
    product = models.OneToOneField(Product, on_delete=SET_NULL, null=True)
    created_at = models.DateTimeField(auto_now_add=True, )
    is_ordered = models.BooleanField(default=False)

    def __str__(self):
        return '{} - {}'.format(self.product, self.quantity)

    class Meta:
        ordering = ('product',)  # This defines how we can order products


class CartAddProductForm(forms.ModelForm):
    class Meta:
        model = OrderItem
        fields = ['quantity']

views.py

def add_to_cart(request, id):
    if request.method == "POST":
        form = CartAddProductForm(request.POST)
        user_profile = get_object_or_404(Profile, user=request.user)
        product = get_object_or_404(Product, id=id)
        if form.is_valid():
            quantity = form.cleaned_data['quantity']
            quantity.save()

            order_item, status = 
                 OrderItem.objects.get_or_create(product=product)
            user_order, status = 
                 Order.objects.get_or_create(owner=user_profile)
            user_order.items.add(order_item) 
            print (quantity)

        context = {'form': form, 'quantity': quantity, }
        return render(request, 'cart/cart_details.html', context)

所有这些格式,但都不起作用!

0 个答案:

没有答案