Django 无法将评论正确保存到 post

Django can't save comment to post properly

我想为我的 post 保存评论,但由于某些原因,视图 returns(如果我输入错误的验证码):

The view MyProject.views.comment_new didn't return an HttpResponse object. It returned None instead.

知道这种行为的原因是什么吗? 遗憾的是,这是唯一一个 place/form 似乎我的验证码被忽略的地方

template.html:

forms.py

首先,它会return错误:

Didn't return an HttpResponse object

因为如果你的 form.is_valid() returns False 没有执行路径可以继续,因此 None 是 returned.

您需要这样做:

def comment_new(request, pk):
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            post = get_object_or_404(Post, pk=pk)
            comment = form.save(commit=False)
            comment.author = request.user
            comment.published_date = timezone.now()
            comment.post = post
            comment.save()
            return redirect('post_detail', pk=comment.post.pk)
        else: # If for is NOT valid:
            form = CommentForm(request.POST)
            return render(request, 'MyProject/comment_new.html', {'form': form})
    else:
        form = CommentForm()
        return render(request, 'MyProject/comment_new.html', {'form': form})

或者为了防止您的代码在视觉上重复(保持"DRY"):

def comment_new(request, pk):
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            post = get_object_or_404(Post, pk=pk)
            comment = form.save(commit=False)
            comment.author = request.user
            comment.published_date = timezone.now()
            comment.post = post
            comment.save()
            return redirect('post_detail', pk=comment.post.pk)
    else:
        form = CommentForm()

    # Note the indentation (this code will be executed both if NOT POST
    # and if form is not valid.
    return render(request, 'MyProject/comment_new.html', {'form': form})

这一行

if form.is_valid():

应该有一个 else 分支,否则它将 return None