【问题标题】:Dynamic URL with variable django template带有可变 django 模板的动态 URL
【发布时间】:2016-08-23 01:20:36
【问题描述】:

我正在尝试基于页面列表构建一个动态的 url 列表。

在我的 urls.py 中,整个应用程序位于命名空间 base 后面:

urlpatterns = patterns('',
    url(r'^(?P<pk>[\w]+)/title/$', TitleSection.as_view(), name='title'),
    url(r'^(?P<pk>[\w]+)/amount/$', AmountSection.as_view(), name='amount'),
    url(r'^(?P<pk>[\w]+)/description/$', DescriptionSection.as_view(), name='description'), )

在我的context 数据中,我有以下列表:

sections: ['title', 'amount', 'description']

我正在尝试为部分中的每个元素构建 url。

我尝试了以下方法:

{% for section in sections %}
    <a href="{% url "base:"+section pk=object.id %}">..</a>
{% endfor %}

但我收到以下错误:

无法解析余数:'+section' from '"base:"+section'

然后我尝试了:

<a href="{% url "base:{{section}}" pk=project.id %}">{{ section }}</a>

错误:

未找到带有参数“()”和关键字参数“{u'pk': 77}”的“{{section}}”的反向操作。尝试了 0 个模式:[]

你知道怎么做吗?

【问题讨论】:

  • 尝试从href中去掉"" 如:..

标签: python django django-views django-urls


【解决方案1】:

您可以使用add template filter:

{% url "base:"|add:section pk=project.id %}

【讨论】:

    【解决方案2】:

    对于我的情况也有效

    {% for section in sections %}
    <a href="{% url "base" pk=object.id %}">..</a>
    {% endfor %}
    

    网址格式在哪里

    url=[
    path('base/<pk>/',base,name='base'),
    ]
    

    【讨论】:

      【解决方案3】:

      我的每个模型都有一个列表视图、一个创建/更新视图和一个删除视图。这些将由客户组织内的不同职能部门使用,以维护他们负责的数据。每个列表视图都有指向相关创建、更新和删除视图的链接。我想建立一个页面,其中包含指向列表视图的链接列表。以下是我的做法。

      我在views.py 中创建了一个基于函数的视图。

      def index(request):
           app     = request.resolver_match.app_name
           models  = apps.get_app_config(app).get_models()
           names   = [model._meta.model.__name__ for model in models]
           context = {
               "names" : names,
           }
           return render(request, app + '/index.html', context)
      

      我创建了一个模板 app/templates/app/index.html

      {% for name in names %}
      <li><a href="{% url request.resolver_match.app_name|add:':'|add:name|lower|add:'-review'%}">{{ name}}</a></li>                                              
      {% endfor %}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-04-11
        • 1970-01-01
        • 1970-01-01
        • 2020-01-02
        • 2017-03-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多