Redirect and Render in Django

Asked

Viewed 2,166 times

1

I have a file views.py which has the following method:

def alterar(request, pk):
    cliente = get_object_or_404(Cliente, pk=pk)    
    if request.method == 'POST':
        form = ClienteForm(request.POST, instance = cliente)
            if form.is_valid():
                cliente = form.save(commit=False)
                cliente.save()
                cliente_listar = Cliente.objects.all()
                return render(request, 'cliente/listar.html', {'cliente' : cliente_listar}) 
    else:
        form = ClienteForm(instance=cliente)
        return render(request, 'cliente/cadastro.html', {'form' : form})

My problem is in render() of POST, because back to url of list you still get the following url: http://127.0.0.1:8000/cliente/alterar/5/, but with the page of list, the right in my view would have to be: http://127.0.0.1:8000/cliente/listar/.

In some researches I found the redirect() but equal to url is in that format: http://127.0.0.1:8000/cliente/alterar/5/cliente/listar.html in which you end up making a mistake.

I’m using Python 3.5 and Django 1.10

1 answer

1


The render() function does not change the url, only what is displayed by it. The correct one would actually be to use redirect() in conjunction with Reverse(). The job of Reverse is to find the full url by name and not by link, as well as to assemble it with the parameters. Here is an example:

return HttpResponseRedirect(reverse('listar', kwargs={'cliente': 5}))

Of course it will depend on how your.py urls are and what parameters your "list" url needs.

Source: https://docs.djangoproject.com/ja/1.10/ref/urlresolvers/#Reverse

Browser other questions tagged

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