【问题标题】:I cannot submit the comments for multi posts in Django我无法在 Django 中提交多个帖子的评论
【发布时间】:2021-05-16 15:53:43
【问题描述】:

我有一个提要,在这个提要中有帖子,每个帖子都有 cmets,现在我可以只为第一个帖子提交评论,但是当我尝试来到第二个或第三个帖子并提交评论时,这个错误就会上升

ValueError:视图 videos.views.add_comment_post 未返回 HttpResponse 对象。它返回 None 。

我认为帖子 id 的问题相互冲突,所以我将所有评论字段传递给模板,但仍然发生相同的错误。 “除了第一个帖子之外的任何帖子都会出现这个问题”

我的 cmets 视图

   comment_form = PostCommentForm(request.POST )
        if comment_form.is_valid():
            user_comment = comment_form.save(commit=False)
            user_comment.author = request.user
            user_comment.save()
            result = comment_form.cleaned_data.get('content')
            user = request.user.username

            return JsonResponse({'result': result, 'user': user})

我的帖子模型

class Post(models.Model):
     author = models.ForeignKey(Account, on_delete=models.CASCADE)
    article = models.TextField(null=True, blank=True)
    photo_article = models.ImageField(max_length=255, upload_to=get_poster_filepath)
    created_date = models.DateTimeField(auto_now_add=True)

我的 cmets 模型

class PostCommentIDE(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='ide_com')
    author = models.ForeignKey(Account, on_delete=models.CASCADE)
    content = models.TextField()
    created_date = models.DateTimeField(auto_now_add=True)

我的 cmets 表单

class PostCommentForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
    class Meta:
        model = PostCommentIDF
        fields = {'post', 'content'}
        widgets = {
            'content': forms.Textarea(attrs={'class': 'rounded-0  form-control', 'rows': '1', 'placeholder': 'Comment', 'required': 'True', })
        }
    def save(self, *args, **kwargs):
        PostCommentIDF.objects.rebuild()
        return super(PostCommentForm, self).save(*args, **kwargs)

【问题讨论】:

  • if comment_form.is_valid() 你的表单无效,它需要一个 else 块,当表单无效时添加逻辑。
  • 谢谢你的回答,我不知道为什么我可以成功提交第一个评论,但我不能提交第二个或第三个帖子的评论
  • 检查您的comment_form.errors 以获取错误。
  • 没有发生任何事情,但这会在终端中显示` "POST /video/post/add/comment HTTP/1.1" 500 70598`

标签: django django-models django-views django-templates


【解决方案1】:

当表单无效时,表单返回 None。
当表单无效时,您应该返回一些东西(例如返回错误消息)。

comment_form = PostCommentForm(request.POST)
if comment_form.is_valid():
    user_comment = comment_form.save(commit=False)
    user_comment.author = request.user
    user_comment.save()
    result = comment_form.cleaned_data.get('content')
    user = request.user.username

    return JsonResponse({'result': result, 'user': user})
else:
    # do stuff here if form is not valid
    return JsonResponse({'result': 'Something went wrong.'}) 

【讨论】:

    猜你喜欢
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    相关资源
    最近更新 更多