我正在关注构建我的第一个电子商务应用程序的教程。我有点卡在他的“添加到购物车”视图中。
请帮助我在我不理解的视图中详细解释一些代码行。我将在要详细了解的代码行之前写“ Detail”一词。
首先是模型
User = get_user_model()
def looping():
filename = item.name
class Item(models.Model):
name = models.CharField(max_length = 210)
detail = models.TextField()
more_detail = models.TextField(null=True)
created = models.DateTimeField(auto_now_add =True)
image = models.ImageField(upload_to = "media/" + time.strftime("%H-%m-%Y"),default = 'https://source.unsplash.com/random/232x266/')
image2 = models.ImageField(upload_to = "media/" + time.strftime("%H-%m-%Y"),default = 'https://source.unsplash.com/random/232x267/')
image3 = models.ImageField(upload_to = "media/" + time.strftime("%H-%m-%Y"),default = 'https://source.unsplash.com/random/232x266/')
slug = models.SlugField()
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super().save(*args, **kwargs)
def get_absolute_url(self):
return reverse('item:detail',kwargs = {"slug":self.slug})
initial_price = models.FloatField(null=True)
price = models.FloatField()
CATEGORY_CHOICES = (
('Men','Men'),
('Women','Women'),
('Kids','Kids')
)
category = models.CharField(choices = CATEGORY_CHOICES,max_length = 210,default = "Men")
label_CHOICES = (
('Hot','Hot'),
('Trending','Trending'),
('few','Few stocks left')
)
label = models.CharField(choices = label_CHOICES,max_length = 210,default = "Hot")
def __str__(self):
return self.name
class OrderItem(models.Model):
user = models.ForeignKey(User,on_delete = models.CASCADE)
item = models.ForeignKey(Item,default=False,null=True,blank=True,on_delete = models.CASCADE)
def __str__(self):
return self.item
class Order(models.Model):
user = models.ForeignKey(User,on_delete = models.CASCADE)
order = models.ManyToManyField(OrderItem,default=False,blank=True)
start_date = models.DateTimeField(auto_now_add=True)
ordered_date = models.DateTimeField()
ordered = models.BooleanField(default=True)
def __str__(self):
return self.order
这是风景
def add_to_cart(request, slug):
item = get_object_or_404(Item, slug=slug)
order_item, created = OrderItem.objects.get_or_create(
item=item,
user=request.user,
ordered=False
)
order_qs = Order.objects.filter(user = request.user,ordered = False)
if order_qs.exists():
order = order_qs[0]
if order.items.filter(item__slug=item.slug).exists():
order_item.quantity += 1
order_item.save()
messages.info(request, "This item quantity was updated.")
return redirect("core:order-summary")
else:
order.items.add(order_item)
messages.info(request, "This item was added to your cart.")
return redirect("core:order-summary")
else:
ordered_date = timezone.now()
order = Order.objects.create(
user=request.user, ordered_date=ordered_date)
order.items.add(order_item)
messages.info(request, "This item was added to your cart.")
return redirect("core:order-summary")