View didn't return an HttpResponse object. It returned None instead

29,361

Solution 1

You are redirecting if form.is_valid() but what about the form is invalid? There isn't any code that get's executed in this case? There's no code for that. When a function doesn't explicitly return a value, a caller that expects a return value is given None. Hence the error.

You could try something like this:

def edit(request, row_id):
    rating = get_object_or_404(Rating, pk=row_id)
    context = {'form': rating}
    if request.method == "POST":
        form = RatingForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home.html')
        else :
            return render(request, 'ratings/entry_def.html', 
                          {'form': form})
    else:
        return render(
            request,
            'ratings/entry_def.html',
            context
        )

This will result in the form being displayed again to the user and if you have coded your template correctly it will show which fields are invalid.

Solution 2

I was with this same error, believe it or not, was the indentation of Python.

Share:
29,361
user3251349
Author by

user3251349

Updated on July 09, 2022

Comments

  • user3251349
    user3251349 almost 2 years

    The view below is gives me the error when using the POST method. I'm trying to load the model data into a form, allow the user to edit, and then update the database. When I try to Save the changes I get the above error.

    def edit(request, row_id):
        rating = get_object_or_404(Rating, pk=row_id)
        context = {'form': rating}
        if request.method == "POST":
            form = RatingForm(request.POST)
            if form.is_valid():
                form.save()
                return redirect('home.html')
        else:
            return render(
                request,
                'ratings/entry_def.html',
                context
            )
    

    Here is the trace from the terminal.

    [15/Apr/2016 22:44:11] "GET / HTTP/1.1" 200 1554
    [15/Apr/2016 22:44:12] "GET /rating/edit/1/ HTTP/1.1" 200 919
    Internal Server Error: /rating/edit/1/
    Traceback (most recent call last):
       File "/Users/michelecollender/ENVlag/lib/python2.7/site-packages/django/core/handlers/base.py", line 158, in get_response
        % (callback.__module__, view_name))
    ValueError: The view ratings.views.edit didn't return an HttpResponse object. It returned None instead.
    
  • e4c5
    e4c5 about 8 years
    Glad to have helped. Since you are a new user here, permit me to point out that if the problem is solved, it's customary to mark the answer as correct. This helps someone who lands on this page in the future from a google search.
  • user3251349
    user3251349 about 8 years
    aha! I was like how do you do that? but I got it. thanks again.