视图未返回HttpResponse对象。它返回None [英] View didn't return an HttpResponse object. It returned None instead

查看:276
本文介绍了视图未返回HttpResponse对象。它返回None的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的视图给我使用POST方法时的错误。我正在尝试将模型数据加载到表单中,允许用户进行编辑,然后更新数据库。当我尝试保存更改时,出现上述错误。

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.


推荐答案

如果格式,您正在重定向.is_valid()但是表格无效吗?在这种情况下没有执行任何代码?没有代码。当函数未明确返回值时,期望返回值的调用方将得到 None 。因此,错误。

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.

您可以尝试如下操作:

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.

这篇关于视图未返回HttpResponse对象。它返回None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆