View in Django does not return HttpResponse object

3

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

  

The view agenda.views.add does not return an HttpResponse object.

Here is the code for the "add" view 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 meaningful answers. How can I fix this error?

    
asked by anonymous 17.03.2014 / 07:03

2 answers

4

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

Try a standard response at the end of the method 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))
    
17.03.2014 / 09:41
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))
    
23.09.2015 / 18:22