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
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:
url
attribute of a generic class-based view.login_url
argument for the django.contrib.auth.decorators.permission_required()
decorator)