user10000033
user10000033

Reputation:

Django can't save comment to post properly

i want to save a comment for my post but for some reasone the view returns (if i enter a wrong captcha):

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

Any idea what could be the reason for this behaviour? Sadly this is the only place/form where it seems that my captcha simply get ignored

template.html:

forms.py

Upvotes: 0

Views: 192

Answers (2)

lch
lch

Reputation: 2188

This line

if form.is_valid():

should have an else branch or else it will return None

Upvotes: 1

coler-j
coler-j

Reputation: 2129

Firstly, it will return the error:

Didn't return an HttpResponse object

Because if your form.is_valid() returns False there is no execution path to continue on, and thus None is returned.

You would need to do this:

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})

Or to keep your code from visually repeating (keep thing "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})

Upvotes: 0

Related Questions