我的models.py文件是:
class Product(models.Model):
title = models.CharField(max_length=110)
slug = models.SlugField(blank=True, unique=True)
price = models.DecimalField(decimal_places=2, max_digits=6)
discount_price=models.FloatField(blank=True, null=True)
size = models.CharField(choices=SIZE_CHOICES, max_length=20)
color = models.CharField(max_length=20, blank=True, null=True)
image = models.ImageField(upload_to=upload_image_path)
description = models.CharField(max_length=1000)
featured = models.BooleanField(default=False)
author = models.ForeignKey(User, on_delete=models.CASCADE)
time_stamp = models.DateTimeField(auto_now_add=True)
objects=ProductManager()
def get_absolute_url(self):#i use this in product_list.html to go to detail page
#return "/product/{slug}".format(slug=self.slug)
return reverse("products:detail", kwargs={"slug" : self.slug})
def __str__(self):
return str(self.title)
@property
def name(self): #sometime in html i say name istead of title so to make it work i wrote this
return self.title
def product_pre_save_reciever(sender, instance, *args, **kwargs):#i inherit unique slug generator from utils to here so when i create aa new instance it slug automatically generate. and i i create two t shirts it give a random straing to tshirt 2nd slug
if not instance.slug:
instance.slug=unique_slug_generator(instance)
pre_save.connect(product_pre_save_reciever, sender=Product)
class Comment(models.Model):
product=models.ForeignKey(Product , related_name="comments", on_delete=models.CASCADE)
name = models.CharField(max_length=255)
body=models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s'%(self.product.title, self.name)
我希望鼻涕条字段继承它到评论,因为评论必须我在他们的特定帖子。当我运行服务器并发表评论时,它是在特定的帖子上发表评论,但给了我评论没有属性段塞的错误。我的views.py文件是:
class CommentCreateView(CreateView):
model = Comment
form_class = CommentForm
template_name = 'add-comment.html'
# fields = '__all__'
def form_valid(self, form):
form.instance.product = Product.objects.get(slug=self.kwargs['slug'])
return super().form_valid(form)
# success_url = reverse_lazy('products:detail')
def get_success_url(self):
return reverse('detail', kwargs={'slug': self.object.slug})
注释没有段符,您只需引用product段符即可。将get_success_url更改为:
def get_success_url(self):
return reverse('detail', kwargs={'slug': self.object.product.slug})
您应该使用self.kwargs['slug']
而不是self.object.slug
来消除错误。
def get_success_url(self):
return reverse('detail', kwargs={'slug': self.kwargs['slug']})