Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a variable in redirect in Django

I'm trying to pass a variable using the redirect function, but it is returning none.

def one:
    # define location variable here
    return redirect(getting_started_info, location=location)

def getting_started_info(request, location=''):
    location = location
    ...

Could someone please tell me why the variable in the redirect is not passing?

like image 291
David542 Avatar asked May 22 '11 03:05

David542


People also ask

Can we pass data with redirect in Django?

You can now perform a redirect with Django, either by using the redirect response classes HttpResponseRedirect and HttpResponsePermanentRedirect , or with the convenience function django. shortcuts. redirect() .

How do you pass arguments in Django redirect?

shortcuts and for redirection to the Django official website we just pass the full URL to the 'redirect' method as string, and for the second example (the viewArticle view) the 'redirect' method takes the view name and his parameters as arguments.

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.


2 Answers

return HttpResponseRedirect(reverse('getting_started_info', kwargs={'location': location}))
like image 97
David542 Avatar answered Oct 11 '22 12:10

David542


Remember that redirect() isn't doing a direct call to your view, it's actually sending the client's browser a 302 Found status (301 Moved Permanently if you use permanent=True) with an instruction to redirect to a different URL. In this case, that URL is one that resolves to the getting_started_info view.

I believe that for this to work, there must exist a urlconf which maps to getting_started_view and which uses its location positional argument. This will most likely occur through named groups.

From the django 1.8 docs entry on redirect():

The arguments could be:

  • A model: the model’s get_absolute_url() function will be called.
  • A view name, possibly with arguments: urlresolvers.reverse will be used to reverse-resolve the name.
  • An absolute or relative URL, which will be used as-is for the redirect location.
like image 38
Ben Burns Avatar answered Oct 11 '22 12:10

Ben Burns