Please help me take a look at this question.
I just find out there are some ways to create a link in Django:
1. <a href='/blog/{{ object.id }}'>{{ object.title }}</a>
2. <a href='{% url "blog:detail" id=object.id %}'>{{ object.title }}</a>
3. <a href='{{ object.get_absolute_url }}'>{{ object.title }}</a>
When should I use these pattern? Are there any special for earch one? Thank you so much.
CodePudding user response:
You can choose whichever you want.
I prefer the second one though.
CodePudding user response:
Usually if you redirect to the canonical page of an object, it makes sense to use the .get_absolute_url()
method [Django-doc]. The get_absolute_url()
method should however make use of the reverse(…)
function [Django-doc] to specify the name of the view, so your model should look like:
from django.urls import reverse
class MyModel(models.Model):
def get_absolute_url(self):
return reverse('blog:detail', kwargs={'id': self.pk })
This will ensure that it will properly URL encode the data in the primary key, and link to the correct path if you later reorganize URLs (but you should actually not reorganize URLs in the first place, see the Cool URLs don't change publication of the W3 organization).
If your model has no canonical URL, or you want to link to something different, it is better to work with the {% url … %}
template tag [Django-doc]. This template tag does a lot of work behind the curtains: (1) it looks up the view name; (2) it will raise an error if it can not find that view, or if the parameters are not compliant; (3) it will URL encode URL parameters; and (4) it will ensure that by writing absolute URLs, this will not visit a path that due to relative paths does not exist.
Constructing manual paths, like you do in the first example is not a good idea. If the {{ object.id }}
for example contains a question mark (?
) or a hash (#
), it will not render these characters without URL encoding these properly, and thus construct an invalid URL.