Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

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

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.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...