当用户使用我想要的CreateView创建帖子时,因此当用户提交帖子时,他们随后将看到他们刚发表的帖子。但是由于某种原因,我的get_absolute_url()
无法正常工作。
在此之前,我开始研究Post和Category模型的功能,由于get_absolute_url
无效,因此无法查看它们是否有效。
型号:
class Category(models.Model):
title = models.CharField(max_length=200)
colorcode = models.CharField(max_length=20, blank=True, null=True)
description = models.TextField()
image = models.ImageField(blank=True, null=True)
slug = models.SlugField(unique=True)
def __str__(self):
return self.title
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True)
image = models.ImageField(blank=True, null=True)
live = models.BooleanField(default=False)
slug = models.SlugField(unique=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'slug': self.slug})
def create_slug(instance, new_slug=None):
slug = slugify(instance.title)
if new_slug is not None:
slug = new_slug
qs = Post.objects.filter(slug=slug).order_by("-pk")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().pk)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_reciever(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_reciever, sender=Post)
观看次数:
class IndexView(ListView):
model = Post
queryset = Post.objects.filter(live=True)
template_name = "public/index.html"
class PostEdit(object):
model = Post
fields = '__all__'
success_url = '/'
class PostCreateView(LoginRequiredMixin, PostEdit, CreateView):
fields = ['title', 'text', 'category', 'image']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin, PostEdit, UpdateView):
fields = ['title', 'text', 'category', 'image']
如果有人对如何解决此问题有任何想法,那就太好了!
答案 0 :(得分:2)
如果按照此定义行事:
class PostEdit(object):
model = Post
fields = '__all__'
success_url = '/' # <<<---
在您的情况下,success_url
不是静态的,不能定义为属性。您必须这样改写get_success_url:
def get_success_url(self):
return self.get_object().get_absolute_url()
也可以看看这个answer。
如果重定向是如此简单,如Daniel Roseman所述,您根本不需要指定success_url
-您想要的是default behavior。
您甚至不需要为CreateView或UpdateView提供success_url-它们将在模型对象上使用get_absolute_url()(如果可用)。