I have just stated to learn Django. So far I pass dynamic URL parameters into reverse function inside the get_absolute_url() method in the following ways:
# By using kwargs:
def get_absolute_url(self):
return reverse('book-detail', kwargs={'id':self.id})
# Or by using the args:
def get_absolute_url(self):
return reverse('book-detail', args=[self.id])
# But I found several examples of the following code:
def get_absolute_url(self):
return reverse('book-detail', args=[str(self.id)]
I have used the simple library app to pass id of the book into URL in order to get book details. All three variants work fine without any problem. Can somebody explain to me why and when we should use args=[str(self.id)]?
Using args=[str(self.id)]
works because you are not using self.id as an int when you create a URL via reverse(), but as part of the string that makes up a URL. The Reverse function actually converts it to a (urlescaped) string as part of its process.
So you never actually have to use str(), it's redundant as it already happens later in the process, but it won't break anything either.