Difference between reverse() and reverse_lazy() in

2020-05-22 16:17发布

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 urls are loaded when we call reverse from the FBV?

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

Does my question makes sense?

标签: python django
2条回答
戒情不戒烟
2楼-- · 2020-05-22 16:58

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 :)

查看更多
▲ chillily
3楼-- · 2020-05-22 17:16
#importme.py
def 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.

查看更多
登录 后发表回答