4

I'm trying to wrap my head around Django concepts, but I struggle with the URLResolver reverse_lazy(). As far as I know, I have to use reverse_lazy() when I want to reverse to an URL that has not been loaded. So when I create a CBV and state a success_url, I use reverse_lazy(). This means that the URL is not imported when the file executes.

This is confusing to me because I think the server loads all the URLs while starting before executing anything. So how come the URL is not loaded in time of execution?

I would be very happy if someone would give me an answer to this.

Xen_mar
  • 8,330
  • 11
  • 51
  • 74
  • check this out if you are still in trouble - https://medium.com/@djerahahmedrafik/django-1-11-reverse-or-reverse-lazy-18990e7db2db – Beginner Aug 21 '20 at 19:05

1 Answers1

6

Well, first of all, the URL resolver itself is lazy, so loading happens when the first call to resolve() or reverse() is made (usually on the first request). But that doesn't matter much in this case.

When the URL resolver is being initialised, it imports your URL configuration, which in turn imports your views. So at the time your view is imported and success_url is set, the resolver is only halfway through its initialisation. Calling reverse() at this point would not work since the resolver doesn't have all the information yet to reverse the view name.

knbk
  • 52,111
  • 9
  • 124
  • 122