简体   繁体   English

如何在模型文件的Django中按名称访问获取URL地址(例如模板的{{url'urlname'}})

[英]How to access to get URL address by name in Django at model file (like {{ url 'urlname' }} at template)

Need to access URL by name at model, can't just hardcode it. 需要在模型上按名称访问URL,而不仅仅是对其进行硬编码。 Need it for error message for a new object creating. 需要它来生成新对象的错误消息。 Any suggestions? 有什么建议么?

Update: Just need to put url to error message, not reverse 更新:只需将URL放入错误消息,而不是反向

您的问题尚不完全清楚,但我认为您正在询问reverse功能。

You can define get_absolute_url method in your model and than access it in other model's methods. 您可以在模型中定义get_absolute_url方法,然后在其他模型的方法中访问它。 Check https://docs.djangoproject.com/en/2.1/ref/models/instances/#get-absolute-url 检查https://docs.djangoproject.com/zh-CN/2.1/ref/models/instances/#get-absolute-url

I suggest you use a template tag. 我建议您使用模板标签。 You can build one for your model and avoid polluting the model about stuff not related to the domain level and keep the presentation level to the template. 您可以为模型构建模型,避免对模型进行与域级别无关的内容的污染,并将表示级别保持在模板范围内。

Check the docs here on how add a templatetags your app.: https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/ 在此处查看有关如何为您的应用添加模板标签的文档。: https : //docs.djangoproject.com/en/2.1/howto/custom-template-tags/

Here a snippet of code to use as starting point for your url generation 这是一小段代码,可以用作生成网址的起点

from django import template

register = template.Library()

@register.simple_tag(takes_context=True)
def url_for_object(context, object):
    # you have both the context and the object available to
    # generate your url here
    url = ....
    return url

In your template use 在您的模板中使用

{% url_for_object my_object %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM