代码之家  ›  专栏  ›  技术社区  ›  Taras

如何在Django at model文件(比如{URL'urlname'}}at template)中访问通过名称获取URL地址

  •  0
  • Taras  · 技术社区  · 6 年前

    需要访问模型的名称网址,不能只是硬编码。创建新对象时需要它作为错误消息。有什么建议吗?

    只需要把错误信息的网址,而不是反向

    3 回复  |  直到 6 年前
        1
  •  1
  •   Daniel Roseman    6 年前

    你的问题不太清楚,但我想你是在问 reverse 功能。

        2
  •  0
  •   UroÅ¡ Trstenjak    6 年前

    你可以定义 get_absolute_url 方法,而不是在其他模型的方法中访问它。检查 https://docs.djangoproject.com/en/2.1/ref/models/instances/#get-absolute-url

        3
  •  0
  •   Karim N Gorjux    6 年前

    查看此处有关如何为应用程序添加模板标签的文档: https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/

    这里有一段代码,可以作为url生成的起点

    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
    

    {% url_for_object my_object %}