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


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

  • As a named parameter segment
  • As a querystring parameter
  • 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
    
    链接地址: http://www.djcxy.com/p/56560.html

    上一篇: Django表单对django无效

    下一篇: 无法在HttpResponseRedirect中传递参数