Django View不返回httpresponse

时间:2018-04-30 22:32:03

标签: python django web django-views

我有以下代码来处理一个简单的表单,我的视图不会发回一个http响应。

我无法弄清楚我的代码有什么问题..

def novo_material(request):
current_page='material'
if request.method =='POST':
    form = SystemInventoryUpdate(request.POST)
    if form.is_valid():
        name=form.cleaned_data['name']
        qty=form.cleaned_data['qty']
        unit=form.cleaned_data['unit']
        t= NewMaterial(name=name,qty=qty,unit=unit)
        t.save()
        return HttpResponseRedirect(reverse('material'))
else:
    form=NewMaterial()
    return render(request,'novo_material.html',{'form':form})

提出此错误:

The view dashboard.views.novo_material didn't return an HttpResponse object. It returned None instead.

2 个答案:

答案 0 :(得分:4)

您处理的情况是请求是POST还是您没有处理无效形式的条件(内部if-else条件)。

 if form.is_valid():
        name=form.cleaned_data['name']
        qty=form.cleaned_data['qty']
        unit=form.cleaned_data['unit']
        t= NewMaterial(name=name,qty=qty,unit=unit)
        t.save()
        return HttpResponseRedirect(reverse('material'))
 else:
    # NEED HANDLE THIS CASE WHEN FORM ISN'T VALID
    # DISPLAY ERRORS/REMINDERS ON THE SAME PAGE, ALARM USER THE INPUT
    # ARE INVLID

答案 1 :(得分:2)

not form.is_valid()时,您不会返回任何HttpResponse ...

def novo_material(request):
    current_page='material'
    if request.method =='POST':
        form = SystemInventoryUpdate(request.POST)
        if form.is_valid():
            name=form.cleaned_data['name']
            ''''''
            t= NewMaterial(name=name,qty=qty,unit=unit)
            t.save()
            return HttpResponseRedirect(reverse('material'))

        # No need to add `else` statement, the `return HttpResponseRedirect` above stops the `if`
        # when form is invalid, it will jump to return render, with form validations generated by Django


    else:
        form=NewMaterial()
    return render(request,'novo_material.html',{'form':form})