我的帖子表格有一个评论部分。这都是我的帖子详细信息。发表评论后,您会发现页面未找到错误:http://localhost:8000/post/15/。十五岁以后不存在。每个评论都会添加到帖子中,但错误中的帖子每次都会增加一。
views.py
class PostDetail(DetailView):
model = Post
def get_context_data(self, **kwargs):
data = super(PostDetail, self).get_context_data(**kwargs)
vc = self.object.view_count
self.object.view_count = F('view_count') + 1
self.object.save()
self.object.view_count = vc + 1
initial_comment_data = {
'post': self.get_object(),
}
data['comment_form'] = CommentModelForm(initial=initial_comment_data)
return data
class CommentCreate(LoginRequiredMixin,CreateView):
model = Comment
form_class = CommentModelForm
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
models.py
class Post(models.Model):
title = models.CharField(max_length=100)#title of a post
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE) #if a user is deleted all of their post will be as well
view_count = models.IntegerField(default=0)
post_files = models.FileField(null = True, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
class Comment(models.Model):
post = models.ForeignKey('forum.Post', on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(User, on_delete=models.CASCADE)
text = models.TextField(null=True)
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.text
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
我希望评论像它一样进入正确的帖子,但页面未找到错误。
答案 0 :(得分:0)
Comment.get_absolute_url
方法传递的是pk
的{{1}},而不是comment
。
尝试以下方法:
post
我认为,class Comment(models.Model):
...
def get_absolute_url(self):
# notice I use self.post.pk here instead of self.pk
return reverse('post-detail', kwargs={'pk': self.post.pk})
返回评论的URL是最佳做法。
在您的Comment.get_absolute_url
上,您可以定义一个CreateView
[1]来重定向到get_success_url
。
Post