Django return redirect() with parameters Django return redirect() with parameters python python

Django return redirect() with parameters


Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:

/link/mybackend/?field1=value1&field2=value2&field3=value3

and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET.

So your urlconf would be:

url(r'^link/(?P<backend>\w+?)/$', my_function)

and the view would look like:

def my_function(request, backend):   data = request.GET

and the reverse would be (after importing urllib):

return "%s?%s" % (redirect('my_function', args=(backend,)),                  urllib.urlencode(form.cleaned_data))

Edited after comment

The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

That said, if all you want to do is store the data, then just put it in the session:

request.session['temp_data'] = form.cleaned_data


urls.py:

#...    url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),

views.py:

from django.shortcuts import redirectfrom .models import Elementdef element_info(request):    # ...    element = Element.object.get(pk=1)    return redirect('element_update', pk=element.id)def element_update(request, pk)    # ...


I do like this in django3

redirect_url = reverse('my_function', args=(backend,))parameters = urlencode(form.cleaned_data)return redirect(f'{redirect_url}?{parameters}')