/ add_to_cart / NOT NULL约束处的IntegrityError失败:

时间:2019-10-20 23:39:11

标签: python django class object null

我有一个将商品添加到购物车的视图,但是当我尝试将商品添加到购物车时 Item 模型出现错误NOT NULL约束失败:cart_item.product_id

我创建了一个模型项来捕获所选项

这是我的 models.py

from django.db import models
from django.contrib.auth.models import User
# Create your models here.


class Product(models.Model):
    product_title = models.CharField(null=True, blank=True,max_length=200)
    product_price = models.IntegerField(null=True, blank=True,)
    product_image = models.ImageField(upload_to='cart/products/', null=True, blank=True)

    def __str__(self):
        return self.product_title

class Cart_Bucket(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    create_date = models.DateTimeField(null=True, blank=True,verbose_name='create_date', auto_now=True)
    checked_out = models.BooleanField(default=False, verbose_name='checked_out')

    def __unicode__(self):
        return unicode(self.create_date)

class Item(models.Model):
    cart = models.ForeignKey(Cart_Bucket, verbose_name='cart', on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField(verbose_name='quantity')
    product = models.ForeignKey(Product, verbose_name='product', related_name='product', on_delete=models.CASCADE)

    def __str__(self):
        return u'%d units' % (self.quantity)

Views.py

def add_to_cart(request):
    user = request.user
    if not user.is_authenticated:
        chars = string.ascii_uppercase + string.digits
        user_name = ''.join(random.choice(chars) for _ in range(9))
        password = '1234567a'
        user = User.objects.create(username=user_name, first_name='guest', last_name='guest', email='guest@gmail.com', is_active=True, is_staff=True)
        user.set_password(password)
        user.save()
        user = authenticate(username=user_name, password=password)
        if user:
            login(request, user)

    product_id = request.GET.get('product_id')
    cart = Cart_Bucket.objects.filter(checked_out=False, user=user)
    cart = cart[0] if cart else ''
    if not cart:
        cart = Cart_Bucket.objects.create(user=user)

    Item.objects.create(cart=cart, product_id=product_id, quantity=1)
    print(Item.objects.all)
    return render(request, 'products/products.html')

我的产品.html

{% extends 'home/base.html' %}

{% block body %}

<div class="row">
        {% for products in product %}
        <div class="col-md-6 col-centered">

                <img src="{{ products.product_image.url }}" style="width: 30%;display:block;margin:0 auto;">
                <div class="row">
                    <div class="col-md-2"></div>
                    <div class="col-md-6">
                        <br>
                        <p>{{ products.product_title }}  Price : $ {{ products.product_price }} </p>

                    </div>
                    <div class="col-md-6"></div>
                    <div class="col-md-4">
                        <a href="{% url 'add_to_cart' %}?products_id={{ products.id }}" class="btn btn-success" role="button">Add to Cart</a>
                    </div>
                    <div class="col-md-2"></div>
                </div>    
                <hr>
        </div>

        {% endfor %}
</div>
{% endblock %}

我想在购物车页面上看到add_to_cart物品

1 个答案:

答案 0 :(得分:0)

我认为这引起了问题,因为Item.objects.create()试图在解析所有参数之前先将模型保存到数据库中。根据Django文档,.save()方法比create()方法具有一些优势。如果您像这样更改代码,则应该解决此问题:

newItem = Item()
newItem.cart = cart
newItem.product_id = product_id
newItem.quantity = 1
newItem.save()