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

岁酱吖の 提交于 2019-12-01 23:28:00

问题


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.

回答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.




回答2:


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



来源:https://stackoverflow.com/questions/36657955/view-didnt-return-an-httpresponse-object-it-returned-none-instead

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!