从模型函数返回指定 URL 的链接
好吧,它终于发生了,我偶然发现了一个问题,但谷歌搜索也无济于事。 (尽管我可能只是朝错误的方向看,在这种情况下,任何指向正确方向的指针都会很棒)。
我正在尝试找到一种方法,从模型的函数返回指向命名 url(带有变量参数)的链接。例如,如果我有模型:
class Picture(models.Model):
picture_id = models.AutoField(primary_key=True)
...
def picture_details(self):
return "{%url picture_details " + str(self.picture_id) + " %}"
我想在模板上为图片对象“pic”创建一个链接:
...
<a href="{{pic.picture_details}}" > details </a>
...
该链接到名为“picture_details”的 url。但是,模板中生成的链接是“http://.....{%url picture_details x %}”(x 是 picture_id)。
我知道使用 可以,但是我的情况略有不同,因为链接是动态构建的图像地图的一部分。因此,我希望图像映射字符串:
<area shape="some_shape" coords="some_coords" href="{{pic.picture_details}}"/>
产生一个名为“picture_details”的 url 的链接,参数为 picture_id。
我希望我能够清楚地解释我的问题,但如果需要更多信息,请告诉我。非常感谢您的帮助,
greetz,
marc
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用
reverse
在这种情况下起作用。Reverse
是{% url %}
模板标记的视图端对应部分。从文档中:
You should use the
reverse
function in this case.Reverse
is the view side counterpart of the{% url %}
template tag.From the documentation: