Search code examples
djangoreversefeed

what is the differences between reverse and reverse_lazey methods in Django?


I can't use reverse() method in a class to generate url

for example, reverse() doesn't work in generic views or Feed classes (reverse_lazy() should be used instead)

but I can use reverse() in functions. what is the differences ?

take a look at following:

class LatestPostFeed(Feed):
    title = 'My Django blog'
    # link = reverse_lazy('blog:index')
    description = 'New posts of my blog'

    def items(self):
        return models.Post.published.all()[:5]

    def item_title(self, item):
        return item.title

    def item_description(self, item):
        return truncatewords(item.body, 30)

    def link(self):
        return reverse('blog:index')

the link attribute above only works with reverse_lazy() method. but the link function works with both reverse_lazy() and reverse() methods


Solution

  • reverse returns string and It's similar to the url template tag which use to convert namespaced url to real url pattern.

    reverse_lazy returns object and It's a reverse() function’s lazy version. It’s prevent to occur error when URLConf is not loaded. Generally we use this function in case below:

    • providing a reversed URL as the url attribute of a generic class-based view.
    • providing a reversed URL to a decorator (such as the login_url argument for the django.contrib.auth.decorators.permission_required() decorator)
    • providing a reversed URL as a default value for a parameter in a function’s signature.