Parameters and Redirects
You’ll need a parameterized query string. You can do that by URL encoding a dictionary. Line 9 creates that dictionary with the keyword
"number" and using Python’s
choice() method from the
random library to randomly choose a number between
5. Line 11 looks up the URL that you’re going to redirect to, line 12 turns the dictionary into a query string, and line 13 marries the
base_url from the lookup with a
? and the resulting
Django itself uses this methodology to deal with login redirects. The
@login_required decorator allows you to wrap a view and redirect the user if they hit the URL and aren’t currently authenticated.
Here’s an example. Let’s say your view was
product_edit() and required the user to log in. When the user hits this URL, they’re sent to the admin login with
next set to the original URL they used.
02:22 This is all great and convenient for the user, but you have to remember, this is still a URL that’s going to the browser, which means your user could tamper with it, so you have to be very careful.
Whatever is in that next URL is where the user will be sent. So if you’re writing code like this yourself, you want to make sure that the destination is safe. Fortunately, the writers of Django have thought about this.
@login_required already checks that URL.
02:49 You can take advantage of their code and check it yourself using one of their internal methods. This internal method checks that a URL is relative, that it’s in an allowed list of hosts, and has a valid scheme—i.e. a scheme matching where they came from.
So that’s how to parameterize a redirect. What if instead, you want to redirect using a different status code?
HttpPermanentRedirectResponse are built-in, returning
302, respectively. If you wish to use one of the newer redirect codes, they’re not built into Django.
Become a Member to join the conversation.