db.models.Model.get_absolute_url()

Model.get_absolute_url()

Define a get_absolute_url() method to tell Django how to calculate the canonical URL for an object. To callers, this method should appear to return a string that can be used to refer to the object over HTTP.

For example:

def get_absolute_url(self):
    return "/people/%i/" % self.id

While this code is correct and simple, it may not be the most portable way to to write this kind of method. The reverse() function is usually the best approach.

For example:

def get_absolute_url(self):
    from django.urls import reverse
    return reverse('people.views.details', args=[str(self.id)])

One place Django uses get_absolute_url() is in the admin app. If an object defines this method, the object-editing page will have a “View on site” link that will jump you directly to the object’s public view, as given by get_absolute_url().

Similarly, a couple of other bits of Django, such as the syndication feed framework, use get_absolute_url() when it is defined. If it makes sense for your model’s instances to each have a unique URL, you should define get_absolute_url().

Warning

You should avoid building the URL from unvalidated user input, in order to reduce possibilities of link or redirect poisoning:

def get_absolute_url(self):
    return '/%s/' % self.name

If self.name is '/example.com' this returns '//example.com/' which, in turn, is a valid schema relative URL but not the expected '/%2Fexample.com/'.

It’s good practice to use get_absolute_url() in templates, instead of hard-coding your objects’ URLs. For example, this template code is bad:

<!-- BAD template code. Avoid! -->
<a href="/people/{{ object.id }}/">{{ object.name }}</a>

This template code is much better:

<a href="{{ object.get_absolute_url }}">{{ object.name }}</a>

The logic here is that if you change the URL structure of your objects, even for something simple such as correcting a spelling error, you don’t want to have to track down every place that the URL might be created. Specify it once, in get_absolute_url() and have all your other code call that one place.

Note

The string you return from get_absolute_url() must contain only ASCII characters (required by the URI specification, RFC 2396) and be URL-encoded, if necessary.

Code and templates calling get_absolute_url() should be able to use the result directly without any further processing. You may wish to use the django.utils.encoding.iri_to_uri() function to help with this if you are using unicode strings containing characters outside the ASCII range at all.

doc_Django
2016-10-09 18:35:54
Comments
Leave a Comment

Please login to continue.