views:

27

answers:

1

Hello all,

Well, it has finally happened, and I have stumbled across a problem for which no amount of googleing has helped. (Although I may simply be looking in the wrong direction, in which case, any pointers in the right direction would be great).

I am trying to find a way to return a link to a named url (with variable arguments) from a model's function. For instance, if I were to have the model:

class Picture(models.Model):
    picture_id = models.AutoField(primary_key=True)
    ...
    def picture_details(self):
        return "{%url picture_details " + str(self.picture_id) + " %}"

I would like to create a link for a Picture object 'pic' on the template:

   ...
   <a href="{{pic.picture_details}}" > details </a>
   ...

That links to the url named 'picture_details'. However, the resulting link in the template is 'http://.....{%url picture_details x %}' (x is the picture_id).

I understand using <a href = {% url picture_details pic.picture_id %} /> would work, however my situation is slightly different, as the links are part of a dynamically built image map. So, I would like the image map string:

    <area shape="some_shape" coords="some_coords" href="{{pic.picture_details}}"/>

to result in a link to the url named 'picture_details' with the argument picture_id.

I hope I have been able to explain my problem clearly, but if any more information is needed, please let me know. Many thanks in advance for any help,

greetz,

marc

+3  A: 

You should use the reverse function in this case. Reverse is the view side counterpart of the {% url %} template tag.

from django.core.urlresolvers import reverse

class Picture(models.Model):
    picture_id = models.AutoField(primary_key=True)
    ...
    def picture_details(self):
        return reverse('picture_details', args = [self.picture_id])

From the documentation:

If you need to use something similar to the url template tag in your code, Django provides the following method (in the django.core.urlresolvers module):

Manoj Govindan
Thanks a lot Manoj!
Marc Gouw
I've been trying to figure out what the 'reverse' was for, and its all starting to make sense. Once again, Django documentation is there to save the world from disaster (if you know where to start looking).
Marc Gouw