Friday, February 1, 2013

Re: get_absolute_url with custom extra parameter

I did use {% url %} before, but now it's not suitable for me anymore. The problem is my url pattern is a little more complicated than above example, sorry, I didn't want to confuse your with irrelevant code. I'm trying to implement a kind of SEO-frendly urls using slugfield album.url like this:

    def _get_absolute_url(self, view='t'):
        return reverse('show_album', args=[view, str(self.id)]) + self.url

Of course I can concatenate {% url %} with album.url right in the template to archive the same results, but I believe this would be a really bad practice. The obvious solution is to pass an argument to get_absolute_url. This is what my question was about. Since it's impossible, I'll remain with what I already have:

    def _get_absolute_url(self, view='t'):
        return reverse('show_album', args=[view, str(self.id)]) + self.url
    def get_absolute_url_f(self):
        return self._get_absolute_url('f')
    def get_absolute_url_t(self):
        return self._get_absolute_url('t')
    def get_absolute_url(self):
        return self._get_absolute_url()

Not very nice but at least it works.
Thank you for your answer, I really appreciate your advice.


четверг, 31 января 2013 г., 15:42:28 UTC+4 пользователь Daniel Roseman написал:
On Thursday, 31 January 2013 05:35:05 UTC, Sammael wrote:
Thank you for your answer!

I have a photo album which can be displayed in two modes: full (with url like 'album/id/full') and thumbnails ( like 'album/id/thumbnails' ). I would like 'get_absolute_url' to return a corresponding url depending on the given mode, something like {{ album.get_absolute_url full }} and {{ album.get_absolute_url thumbnails }}

The only solution I could find is to use two different functions: get_absolute_url_full and get_absolute_url_thumbnails. It works but it's ugly, I don't like it at all.

Any advice is greatly appreciated.


You should think about using the `url` tag, which does take arguments and seems to do what you want already:

    {% url 'album_full' album.id %}
    {% url 'album_thubmnail' album.id %}

Then your urls.py looks like this:

    url(r'/album/(?P<id>\d+)/full/$', full_album_view, name='album_full'),
    url(r'/album/(?P<id>\d+)/thumbnails/$', full_album_view, name='album_thumbnail'),
 
and if you still need the `get_absolute_url` function you can use the `@permalink` decorator to reuse the logic in urls.py
--
DR.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments:

Post a Comment