Dom Shahbazi
Dom Shahbazi

Reputation: 730

Django - cant pass parameter in HttpResponseRedirect

I have read that after successfully dealing with post data, you should use HttpResponseRedirect to redirect to another page. I am building a URL shortener for learning purposes, the code from views.py is shown below: (Not working)

def makeurl(request):
    # get url from form
    post_url = request.POST['url']
    # shorten the url and have the short code returned
    shortened_url = shorten_url(post_url)
    return HttpResponseRedirect('create')    

def create(request):
    return render(request, 'shorturl/create.html',
        {'shortened_url': shortened_url}) 

When my form is submitted to shorten the input URL, 'makeurl' is called, where the shortened URL is calculated and returned (shortened_utl). I then call 'create', which will render the page where 'shortened_url needs to be displayed to the user.

The problem is, if i am to use HttpResponseRedirect, i have no way of passing the 'shortened_url' variable to my 'create' view to be rendered. Can anyone advice me with this? Im new to django, cheers

Upvotes: 3

Views: 6101

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34553

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

Upvotes: 5

Related Questions