我正在建立一个具有评论和回复功能的论坛。在填写表格时,我面临一个问题
无法分配“<Post: Post object (10)>”:“Reply.comment”必须是“Comment”实例。 我可以理解这个问题,但不知道如何将它变成评论实例。我正在使用 Django 3.1.4
型号如下:
class Post(models.Model):
headline = models.CharField(max_length = 100)
context = models.TextField()
author = models.ForeignKey(User, on_delete = models.CASCADE)
created = models.DateTimeField(auto_now_add = True)
modified = models.DateTimeField(auto_now = True)
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete = models.CASCADE)
text = models.TextField(max_length = 200)
author = models.ForeignKey(User, on_delete = models.CASCADE)
created = models.DateTimeField(auto_now_add = True)
modified = models.DateTimeField(auto_now = True)
class Reply(models.Model):
comment = models.ForeignKey(Comment, related_name='replies', on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
reply = models.TextField()
view.py 如下:
class PostDetail(DetailView):
model = Post
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['comment_form'] = CommentForm()
context['reply_form'] = ReplyForm()
return context
def post(self, request, *args, **kwargs):
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
comment = Comment(
author = request.user,
post = self.get_object(),
text = comment_form.cleaned_data['comment']
)
comment.save()
else:
comment = Comment()
reply_form = ReplyForm(request.POST)
if reply_form.is_valid():
reply = Reply(
user = request.user,
comment = self.get_object(), # This line is the issue!!!
reply = reply_form.cleaned_data['reply']
)
reply.save()
else:
reply = Reply()
return redirect (reverse('postdetail', args=[self.get_object().id]))
我想这么多信息就足够了。真的需要了解如何去做。
谢谢