Fixed #18974 - Warned against using models.permalink

Thanks dstufft for the draft patch.
This commit is contained in:
Tim Graham 2012-11-20 07:15:16 -05:00
parent 891c530624
commit 0e3690d230
5 changed files with 43 additions and 40 deletions

View file

@ -482,9 +482,13 @@ For example::
return "/people/%i/" % self.id
(Whilst this code is correct and simple, it may not be the most portable way to
write this kind of method. The :func:`permalink() decorator <permalink>`,
documented below, is usually the best approach and you should read that section
before diving into code implementation.)
write this kind of method. The :func:`~django.core.urlresolvers.reverse`
function is usually the best approach.)
For example::
def get_absolute_url(self):
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
@ -529,11 +533,19 @@ in ``get_absolute_url()`` and have all your other code call that one place.
The ``permalink`` decorator
~~~~~~~~~~~~~~~~~~~~~~~~~~~
The way we wrote ``get_absolute_url()`` above is a slightly violation of the
DRY principle: the URL for this object is defined both in the URLconf file and
in the model.
.. warning::
You can decouple your models from the URLconf using the ``permalink`` decorator:
The ``permalink`` decorator is no longer recommended. You should use
:func:`~django.core.urlresolvers.reverse` in the body of your
``get_absolute_url`` method instead.
In early versions of Django, there wasn't an easy way to use URLs defined in
URLconf file inside :meth:`~django.db.models.Model.get_absolute_url`. That
meant you would need to define the URL both in URLConf and
:meth:`~django.db.models.Model.get_absolute_url`. The ``permalink`` decorator
was added to overcome this DRY principle violation. However, since the
introduction of :func:`~django.core.urlresolvers.reverse` there is no
reason to use ``permalink`` any more.
.. function:: permalink()
@ -544,14 +556,14 @@ correct URL, with all parameters substituted in the correct positions.
The ``permalink`` decorator is a Python-level equivalent to the :ttag:`url`
template tag and a high-level wrapper for the
:func:`django.core.urlresolvers.reverse()` function.
:func:`~django.core.urlresolvers.reverse` function.
An example should make it clear how to use ``permalink()``. Suppose your URLconf
contains a line such as::
(r'^people/(\d+)/$', 'people.views.details'),
...your model could have a :meth:`~django.db.models.Model.get_absolute_url()`
...your model could have a :meth:`~django.db.models.Model.get_absolute_url`
method that looked like this::
from django.db import models