[Django]-Django – cant pass parameter in HttpResponseRedirect

5👍

You can easily pass parameters using a redirect in at least three ways:

  1. As a named parameter segment
  2. As a querystring parameter
  3. As a session variable

Let’s say your “create” view takes a parameter called “shortened_url”. Your URL for that using method 1 would look like:

# urls.py
url(r'create/(?P<shortened_url>.)/$', create, name='create',)


# views.py
def create(request, shortened_url):
    # do whatever

In your view that handles the form post, you would do:

from django.core.urlresolvers import reverse

def makeurl(request):
    . . .
    return HttpResponseRedirect(reverse('create', args=(),
        kwargs={'shortened_url': shortened_url}))

If it is method 2, you don’t need the named parameter in the url pattern at all, can instead just reverse the url pattern and tack on the querystring parameter:

def makeurl(request):
    . . .
    url = reverse('create')
    url += '?shortened_url={}' + shortened_url
    return HttpResponseRedirect(url)

If it’s method 3, you don’t need the named parameter or a querystring value:

def makeurl(request):
    . . .
    request.session['shortened_url'] = shortened_url
    return HttpResponseRedirect(reverse('create'))

def create(request):
    shortened_url = request.session.get('shortened_url')
    . . .

    # delete the session value
    try:
        del session['shortened_url']
    except KeyError:
        pass

    # do whatever

Leave a comment