Generating URLs in the Model Class

The Django framework allows you to define an extra method for each model that returns the absolute URL for an object. So, for example, this is how we could define this method for the NetworkAddress class:

def get_absolute_url(self):

return '/networkaddress/%s/%s/' % (self.address, self.network_size)

With this defined, we then can use this function in all templates to get the URL of the object:

<a href="{{ address.get_absolute_url }}">{{ address }}</a>

This allows us to reference object URLs without thinking about the URL structure. All we need is a reference to a URL, and we get that value by referencing the get_absolute_url property of the object. If for whatever reason we decide to change the URL structure, we will not need to alter any of the template code, because references are generated outside it.

Was this article helpful?

0 0

Post a comment