Django 1.11: Reverse or Reverse Lazy
Well reverse and reverse_lazy are two utility functions that we use in our Django projects or apps to redirect from a view to another, basically it’s a more convenient way to deal with urls without hardcoding them.
First let’s say we have an application with two urls one for index and one for the about page.
Now to understand what does reverse and reversy_lazy return let’s create a view called index.
After that let’s navigate to /index/ page and see the outputs
Hmmm didn’t expect that huh ! the same output … so let’s dig deeper and for that i’ll add two lines of code: type(url1) & type(url2) to see what does reverse() and reverse_lazy() return
Conclusion number 1
From that you can say with confidence that reverse() returns a string and reverse_lazy() returns an <object>.
Into the dielmma !
After knowing what does reverse() and reverse_lazy() return let’s see now what dielmma reverse_lazy() comes to solve.
In the views.py files let’s add these two lines of code
Basically i created a RedirectView to the index page and instead of hardcoding the url i used the reverse() function.
Now if you access /about/ from your browser this is what will you get !
And what it says is that “vidly.urls” file does not appear to have any patterns on it even though we are 100% sure that this file does contain a url patterns *on it and the reason why this error appear is that when python is in the process of parsing resolvers.py file it tried to execute the reverse() function so at this point reverse() would not work since the resolver doesn’t have all the information yet to reverse the view name.
In most cases when you find yourself in this kind of situations you should consider using the lazy version of reverse() [reverse_lazy()]
Use cases of reverse_lazy()
Well according to Django 1.11 docummentation you should consider using reverse_lazy() when:
- You want to provide a reversed URL as the url attribute of a Generic Class Based View (the same as we did in our example).
- You want to provide a URL as a default value for a parameter in functions signature.
- You want to provide a URL to a decorator like @login_required(login_url) decorator.
PS: You can watch the video version of this article on my Youtube channel(Link)