RedirectView Class Helper
It is parameterized with a URL of where to go—in this case, Google—and the parameter can be altered using the
%s mechanism. The query string for Google includes
"%(term)s" portion will get filled in with the
term from the
SearchRedirectView inherits from the
RedirectView class. Inside of the
views file, you can see that class. In this case, all I’ve done is override the
.url attribute. The contents of the
.url attribute are exactly the same as directly calling it in the previous example—
"google.com", still using
"%(term)s"—and this will get populated as before.
This is the method in the class that results in the redirect string. By overriding it, you can take complete control over what it does. In this particular example, I’m randomly picking one of the URLs defined in
search_urls—lines 8 through 12—and when I’ve picked it, I parameterize it. Just like before, it supports the
"%(term)s" mechanism, passing in the
term parameter from the
You can specify the
.url attribute for a hardcoded string. Instead, you can set
.pattern_name to specify a named URL pattern. There’s a boolean called
.permanent which defaults to
False, but if set to
True uses a permanent redirect.
The default implementation of
.get_redirect_url() checks for the
.url attribute. If it doesn’t find it, then it checks for the
.pattern_name attribute. Both the
.pattern_name attributes support the
%s placeholders, passing in keyword arguments from the URL pattern. When should you use this class? Well, it’s an easy way of putting a redirect right inside of your
I tend to only use this myself if I’m directly overloading in the
urls file. But if your codebase uses class-based views or you find them easier to understand, that’s what it’s there for. Next up, I’ll show you how to use parameters inside of your redirects.
Become a Member to join the conversation.