【问题标题】:URL output in template is empty模板中的 URL 输出为空
【发布时间】:2012-07-15 03:23:44
【问题描述】:

views.py 中的 URL 模式声明

url(r'^intentions/(\d+)/$', 'intentions.views.show'),

当我直接写地址时,像 intents/1 一样工作正常,但是当我尝试显示对象的 URL 显示时:

{% for i in intentions %}
   {% url 'intentions.views.show' i.id as iUrl %}
    <li><a href="{{ iUrl }}">{{ i }}</a></li>
{% endfor %}

我以空的 href 结尾。有人可以给我任何建议吗?

【问题讨论】:

    标签: django django-templates django-urls


    【解决方案1】:

    如果您使用的是 Django 1.3 或 1.4,请确保您是 loading the new url tag。将以下行添加到模板的顶部:

    {% load url from future %}
    

    如果您使用的是 Django 1.4 或更早版本,并且没有像上面那样加载新的 url 标签,那么您需要从 url 模式中删除单引号:

    {% url intentions.views.show i.id as iUrl %}
    

    顺便说一句,建议name your url pattern

    url(r'^intentions/(\d+)/$', 'intentions.views.show', name='show_intention'),
    

    然后将您的模板更改为:

    {% for i in intentions %}
      {% url 'show_intention' i.id as iUrl %}
      <li><a href="{{ iUrl }}">{{ i }}</a></li>
    {% endfor %}
    

    【讨论】:

      【解决方案2】:

      你可以试试

      {% for i in intentions %}
          <li><a href="{% url 'intentions.views.show' i.id %}"><{{ i }}</a></li>
      {% endfor %}
      

      不要使用 {% url 'intentions.views.show' i.id as iUrl %},它可能会混淆。 另外,您可以尝试修改网址如下

       url(r'^intentions/(\d+)/$', 'intentions.views.show', name="intention_view"),
      

      那么,

      {% for i in intentions %}
           {% url "intention_view" i.id as iUrl %}
           <li><a href="{{ iUrl }}">{{ i }}</a></li>
      {% endfor %}
      

      如果href也有结尾空,试试第一种方法。

      【讨论】:

        【解决方案3】:

        'intentions.views.show'
        还要为您的 URL 提供一个 name='' 并在您的模板代码中使用它。

        【讨论】:

          猜你喜欢
          • 2021-04-19
          • 1970-01-01
          • 2011-04-21
          • 2011-01-03
          • 1970-01-01
          • 2016-04-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多