我有以下代码来处理一个简单的表单,我的观点是不发回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.

最佳答案

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})

关于python - Django View未返回httpresponse,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50109084/

10-09 02:47