我有一个将项目添加到购物车的视图,但是当我尝试将项目添加到购物车时,项目模型引发错误 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商品
我认为这引发了问题,因为Item.objects.create()
尝试先将模型保存到数据库中,然后再解析所有参数。基于Django文档,.save()
方法比create()
方法具有一些优势。如果您更改代码,例如:
newItem = Item()
newItem.cart = cart
newItem.product_id = product_id
newItem.quantity = 1
newItem.save()