Difference between reverse() and reverse_lazy() in Django
#importme.pydef a(): print("FUNCTION HELLO")class B(): print("CLASS HELLO") >>> import importme>>> CLASS HELLO
Class attributes are evaluated on import. The answer to when or exactly how that happens, resides within the depths of python's import system.
Consider these two ways of defining the success_url. The first is commented out,the second is the function:
class NewJobCBV(LoginRequiredMixin, CreateView): template_name = 'company/job.html' form_class = newJobForm # success_url = reverse_lazy('newJob') def get_success_url(self, **kwargs): return reverse("newJob")
@CoffeeBasedLifeform : you are right, class attributes are evaluated on import, I checked after reading your answer. So,
- If we are using
success_url
we have to usereverse_lazy()
. - If we are reversing inside a function we can use
reverse()
.
Now it is crystal clear.
Thanks CoffeeBasedLifeform :)
Just understand the difference:
reverse() returns a string
& reverse_lazy() returns an <object>