Here are resources for more information on Django views and URL patterns:
Django's Redirect Shortcut
In the previous lesson, I introduced you to the concept of an HTTP redirect. In this lesson, I’m going to dive into Django’s
redirect() shortcut, and how to use it. In the introduction, I quickly demonstrated the use of the Django
The default status code is
OK. This needs to be changed to
302, for redirect. Secondly, you have to add a header to the response, which is the location of where you wish to redirect to. Finally, just return that.
You can call it with a reference to a view. Or, you can pass it an object that supports the
get_absolute_url() method. I’ll show you the first three in practice, and then I’ll come back to the object method, later.
This URL can be found in
'details/' URL is parameterized with a
product_id, associated with a view named
details, and tagged with the name
'product-details', for further use later.
The corresponding function in the
views file uses the
redirect() shortcut. This use of the shortcut is using the
"product-details" name tag, associating with the URL having the name
"product-details". It’s parameterized with the
product_id that was passed in.
This mode of redirect is the one I like best. You associate the redirected view with the view that you want to be redirected to. You don’t have to have any knowledge of what’s going on inside of the
urls file. The returned result of this, with the parameter
3, gives you
This view calls the
redirect() shortcut function, passing in a hardcoded URL. It uses the
% string mechanism in order to parameterize the URL. In the demo I gave in the introduction, this was the shortcut that I used. Generally, it’s considered bad practice, though.
It’s bad practice because if you need to change your URL, you now have to remember to change it inside of your view file as well as inside of the
urls file. So it’s good for a quick demonstration but otherwise, you should avoid using this mechanism in production code.
One of the advantages to this is the Django admin is aware of it. If you implement this method on an object model, the Django admin will automatically add a reference link. On the models page, a VIEW ON SITE button is added, redirecting the user to the result of
Become a Member to join the conversation.