View 没有返回 HttpResponse 对象.它返回 None 代替 [英] View didn't return an HttpResponse object. It returned None instead

查看:26
本文介绍了View 没有返回 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
        )

这是来自终端的跟踪.

[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.

推荐答案

如果 form.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.

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

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