怎么解决没有用django返回httpresonse错误?

我在注册django时遇到问题,这是我的观看代码:

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')
    else:
        form = RegistrationForm()

        args = {'form': form}
        return render(request, 'users/reg_form.html', args)

,但我总是得到:

/ error / register /上的ValueError视图Users.views.register未返回HttpResponse对象 . 它返回了None . 请求方法:POST请求URL:http://127.0.0.1:316 / user / register / Django版本:2.0.2异常类型:ValueError异常值:视图Users.views.register未返回HttpResponse对象 . 它返回了None . 异常位置:/home/iah/.local/lib/python3.5/site-packages/django/core/handlers/base.py in _get_response,139行

回答(4)

2 years ago

检查代码并问自己,如果你有一个POST请求会发生什么,并且表单没有发现在这种情况下你没有明确的返回路径,所以函数隐含地返回 None .

修复很简单:取消函数的最后两行,所以当表单没有验证时,你也会返回渲染的模板:

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')

    else:
        form = RegistrationForm()

    # MAKE SURE WE ALWAYS RETURN A RESPONSE:
    # we end up here when it's a GET request 
    # AND when it's a POST request and the form
    # did not validate   
    args = {'form': form}
    return render(request, 'users/reg_form.html', args)

2 years ago

您必须从内部 else 块返回响应:

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')
        else:
            # here 
    ...

2 years ago

如果表单无效且 form.is_valid() 失败,请确保返回一些内容 .

例:

def register(request):
if request.method == 'POST':
    form = RegistrationForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect('/')
    else:
        return redirect('/') # or render(...)/whatever you need to redirect to
else:
    form = RegistrationForm()

    args = {'form': form}
    return render(request, 'users/reg_form.html', args)

希望这可以帮助!

2 years ago

你缺少else代码 . 您的if语句说:如果表单有效,请保存表单 . 但是,如果表单无效,如果用户名是所有特殊字符(例如:!@#%%% ^^),或者如果用户名仅为1字符长ex :(用户名:A),该怎么办?或者如果密码只有3个字符长(例如:pas),在所有这些情况下,用户应该返回空白表格 . 您还应该考虑使用基于类的视图进行注册此链接将help

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        **if form.is_valid():** 
 # What if the form is not valid you haven't accounted for that 
            form.save()
            return redirect('/')
    else:       
 # Adding a else solves this problem. The user gets a blank form back                
        form = RegistrationForm()
        args = {'form': form}
        return render(request, 'users/reg_form.html', args)**