Question

I´m working on my first django project. I´ve been trying to create a simple contact form, but I get the error:

ValueError at /blog/contacto/ The view blog.views.contacto didn't return an HttpResponse object.

def contacto (request):
if request.method == 'POST': #Si e formulario es enviado...
    form = Formulario(request.POST)
    if form.is_valid(): #Si son validos los datos del formulario
        return HttpResponseRedirect('/blog/gracias') #redireccion a gracias
    else:
        form = Formulario() #un Unbound form

    return render(request, 'contacto.html',{'form':form,})

I don´t understand why this is happening, I´ve checked the forms documentation in django and the view I´ve done is almost identical to the one in the documentation.

Can anyone help me out?

Was it helpful?

Solution

Your view doesn't return an HttpResponse if request.method is not POST.

There is an indentation issue. You need to return an unbound form in case the form is not submitted:

def contacto (request):
    if request.method == 'POST': #Si e formulario es enviado...
        form = Formulario(request.POST)
        if form.is_valid(): #Si son validos los datos del formulario
            return HttpResponseRedirect('/blog/gracias') #redireccion a gracias
    else:  # <-- WATCH WHERE ELSE IS
        form = Formulario() #un Unbound form

    return render(request, 'contacto.html',{'form':form,})

Also see this relevant example that describes this standard form view pattern.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top