hopieman
hopieman

Reputation: 389

Django View not returning httpresponse

I have the following code to handle a simple form, my view is not sending back an http response.

I can't figure out what's wrong with my code..

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

It is raising this error:

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

Upvotes: 1

Views: 1466

Answers (2)

Lemayzeur
Lemayzeur

Reputation: 8525

when not form.is_valid(), you do not return any 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})

Upvotes: 2

Haifeng Zhang
Haifeng Zhang

Reputation: 31915

You handle the case whether request is POST but you didn't handle the condition (inner if-else condition) that form is invalid.

 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

Upvotes: 4

Related Questions