Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.2K
Views
Difference between reverse() and reverse_lazy() in Django

I understand that we can use reverse() in FBV and reverse_lazy() in CBV. I understand that we have to use reverse_lazy() in CBV as the urls are not loaded when the file is imported (Ref: Reverse_lazy and URL Loading?)

What I don't understand is:

How are the urls loaded when we call reverse from the FBV? As when we import the views at the top of the urls.py in a Django app, urlpatterns list is yet to be evaluated. How does reverse() for FBV work but not for CBV?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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,

  1. If we are using success_url we have to use reverse_lazy().
  2. If we are reversing inside a function we can use reverse().

Now it is crystal clear.

Thanks CoffeeBasedLifeform :)

over 4 years ago · Santiago Trujillo Report

0

#importme.py
def a():
    print("FUNCTION HELLO")

class B():
    print("CLASS HELLO") 
    

>>> import importme
>>> CLASS HELLO

Edit: The reason: The class creation process involves executing the body of the class.

The class body is executed (approximately) as exec(body, globals(), namespace). [...] Once the class namespace has been populated by executing the class body, the class object is created by calling metaclass(name, bases, namespace, **kwds).

https://docs.python.org/3/reference/datamodel.html?highlight=metaclass#executing-the-class-body



My original answer text. You can ignore it - I'm just leaving it in because mirek's comment was a direct response to it:

Class attributes are evaluated on import. The answer to when or exactly how that happens, resides within the depths of python's import system.

over 4 years ago · Santiago Trujillo Report

0

Just understand the difference:

reverse() returns a string & reverse_lazy() returns an <object>

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!