您好,我想按提交进行交易,这是错误消息
/ cart / update-transaction / 0cqydz1f /上的IntegrityError /不为空 约束失败:shopping_cart_transaction.product_id请求 方法:GET请求 网址:http://localhost:8000/cart/update-transaction/0cqydz1f/ Django 版本:2.2异常类型:IntegrityError异常值:NOT NULL 约束失败:shopping_cart_transaction.product_id
class Transaction(models.Model):
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
product = models.ForeignKey(Product,on_delete=models.CASCADE)
token = models.CharField(max_length=120)
order_id = models.CharField(max_length=120)
amount = models.DecimalField(max_digits=100, decimal_places=2)
success = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
def __str__(self):
return self.order_id
class Meta:
ordering = ['-timestamp']
@login_required()
def update_transaction_records(request, token):
# get the order being processed
order_to_purchase = get_user_pending_order(request)
# update the placed order
order_to_purchase.is_ordered=True
order_to_purchase.date_ordered=datetime.datetime.now()
order_to_purchase.save()
# get all items in the order - generates a queryset
order_items = order_to_purchase.items.all()
# update order items
order_items.update(is_ordered=True, date_ordered=datetime.datetime.now())
# Add products to user profile
user_profile = get_object_or_404(Profile, user=request.user)
# get the products from the items
order_products = [item.product for item in order_items]
user_profile.ebooks.add(*order_products)
user_profile.save()
# create a transaction
transaction = Transaction(profile=request.user.profile,
token=token,
order_id=order_to_purchase.id,
amount=order_to_purchase.get_cart_total(),
success=True)
# save the transcation (otherwise doesn't exist)
transaction.save()
messages.info(request, "Thank you! Your purchase was successful!")
return redirect(reverse('accounts:my_profile'))
请帮助困在这里
答案 0 :(得分:0)
您尚未传递模型中提到的product
的参数。而且由于您没有给它提供默认值,或者给了blank = True
,所以您得到了不受NOT NULL约束的失败错误。
product = models.ForeignKey(Product,on_delete=models.CASCADE)
在此处传递产品对象。
transaction = Transaction(profile=request.user.profile,product = product, ...)
答案 1 :(得分:0)
在您的transaction
中更新您的view
我假设您的order_products
是所有订购的products
的列表
for i in order_products:
transaction = Transaction(profile=request.user.profile,
product=i,
token=token,
order_id=order_to_purchase.id,
amount=order_to_purchase.get_cart_total(),
success=True)
# save the transcation (otherwise doesn't exist)
transaction.save()