我试图从youtube做一个购物车模块,结果遇到了“在/ store / add-to-cart / 1'的TypeError”错误。到目前为止,我一直被这种错误困扰。
因此,这是与该错误有关的代码。 我的views.py:
def add_to_cart(request, product_id):
product = Product.get_object_or_404(pk= product_id)
order_item, status = OrderItem.objects.get_or_create(product=product)
user_order, status = Order.objects.get_or_create(is_ordered=False)
user_order.items.add(order_item)
if status:
user_order.OR = generate_order_id()
user_order.save()
messages.Information(request, 'Item added to cart')
return redirect(reverse('store:index'))
这是我的models.py:
class Product(models.Model):
sku = models.CharField(unique = True, max_length = 200)
barcode = models.CharField(max_length = 200)
name = models.CharField(max_length = 50)
description = models.TextField(max_length = 500, blank=True, validators=[MaxLengthValidator(500)])
base_price = models.DecimalField(max_digits = 5, decimal_places = 2, default = 0)
product_image = models.ImageField(blank = True, null = True, upload_to = 'product_images/%Y/%m/%D/')
number_of_stocks = models.IntegerField(default = 0)
date_created = models.DateField(auto_now_add = True)
category = models.ManyToManyField(Category, default = None)
def __str__(self):
return self.name
# Displays the image
def image_tag(self):
return u'<img src="%s" width="150" height="150" />' % (self.product_image.upload_to)
image_tag.short_description = 'Image'
class OrderItem(models.Model):
product = models.OneToOneField(Product, on_delete=models.SET_NULL, null = True)
is_ordered = models.BooleanField(default=False)
date_added = models.DateTimeField(auto_now=True)
date_ordered = models.DateTimeField(null=True)
def __str__(self):
return self.product.name
class Order(models.Model):
OR = models.CharField(max_length = 15)
# user fk
is_ordered = models.BooleanField(default=False)
items = models.ManyToManyField(Product, default = None)
order_date = models.DateTimeField()
raw_total_price = models.DecimalField(max_digits = 6, decimal_places = 2, default = 0)
delivery_fee = models.DecimalField(max_digits = 6, decimal_places = 2, default = 150)
total_price = models.DecimalField(max_digits = 6, decimal_places = 2, default = delivery_fee)
# order status fk
def get_cart_items(self):
return self.products.all()
def get_cart_total(self):
return sum([item.product.base_price for item in self.items.all()])
def __str__(self):
return self.OR
这是我的urls.py:
urlpatterns = [
path('', views.index, name='index'),
path('<int:product_id>/', views.product, name='product'),
path('checkout/', views.checkout, name='checkout'),
path('signup/', views.signup, name='signup'),
path('signup/success', views.signupsuccess, name='signupsuccess'),
path('add-to-cart/<int:product_id>', views.add_to_cart, name='add_to_cart'),
]