开发者

returning a link to a named URL from a model function

开发者 https://www.devze.com 2023-01-16 21:20 出处:网络
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 i

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 infor开发者_StackOverflowmation is needed, please let me know. Many thanks in advance for any help,

greetz,

marc


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):

0

精彩评论

暂无评论...
验证码 换一张
取 消