0

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

Farid Darabi
  • 59
  • 1
  • 6
  • I hope the [official doc of **`reverse_lazy(...)`**](https://docs.djangoproject.com/en/3.0/ref/urlresolvers/#reverse-lazy) is itself self-explanatory. – JPG Jun 30 '20 at 15:57
  • Thanks but I have already read it but I didn't understand "It is useful for when you need to use a URL reversal before your project’s URLConf is loaded" – Farid Darabi Jun 30 '20 at 16:30
  • @FaridDarabi In which part do you have a problem? – Milad Hatami Aug 14 '20 at 10:19

1 Answers1

1

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.
Ali Aref
  • 1,893
  • 12
  • 31