View in Django does not return Httpresponse object

Asked

Viewed 666 times

4

I am doing a simple CRUD in Django for learning purposes. However, I am having a problem. When creating a view to add data to a schedule, the server returns the following error:

The view agenda.views.adiciona didn’t Return an Httpresponse Object.

Follow the "add" view code I wrote:

def adiciona(request):
    if request.method == "POST":
        form = FormItemAgenda(request.POST, request.FILES)

        if form.is_valid():
            dados = form.cleaned_data
            item = ItemAgenda(data=dados['data'], hora=dados['hora'], titulo=dados['titulo'], descricao=dados['descricao'])
            item.save()
            return render_to_response("salvo.html", {})
        else:
            form = FormItemAgenda()
        return render_to_response("adiciona.html", {'form': form}, context_instance=RequestContext(request))

Set the routes in "urls.py" as follows:

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', 'agenda.views.lista'),
    url(r'^adiciona/$', 'agenda.views.adiciona'),
)

I searched Google and the Django 1.6.x documentation and found no significant response. How can I fix this error?

2 answers

4


If your code is only shown, then what seems to be missing is a else to handle requisitions and not a post. In fact, the render_to_response returns a HttpResponse and, if the problem were an exception, the error message would be another. What might be happening then is that your view is being called with another HTTP method (probably get) and - as there is no else - she be returning None.

Try, at the end of the method, to put a default response if the view does not recognize the method:

def adiciona(request):
    if request.method == 'POST':
        ...
    else:
        return HttpResponse('Método inválido para essa operação: {}'.format(request.method))
  • Thank you for taking my question. In fact he returned the message indicating GET method. Now I need to figure out how to make the form pass the POST method, as it should be...

0

def adiciona(request):
    if request.method == 'POST':
        form = FormCrud(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return render_to_response("salvo.html",{})
    else:
        form = FormCrud() 

    return render_to_response("adiciona.html",{'form':form},context_instance=RequestContext(request))
  • 1

    Could explain what this code does?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.