簡體   English   中英

帶有可變 django 模板的動態 URL

[英]Dynamic URL with variable django template

我正在嘗試基於頁面列表構建一個動態的 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 %}

但我收到以下錯誤:

無法解析剩余部分:來自 '"base:"+section' 的 '+section'

然后我嘗試:

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

錯誤:

使用參數 '()' 和關鍵字參數 '{u'pk': 77}' 反轉 '{{section}}' 未找到。 嘗試了 0 個模式:[]

你知道怎么做嗎?

您可以使用添加模板過濾器

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

對於我的情況也有效

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

網址模式在哪里

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

我的每個模型都有一個列表視圖、一個創建/更新視圖和一個刪除視圖。 這些將由客戶組織內的不同職能部門使用,以維護他們負責的數據。 每個列表視圖都有指向相關創建、更新和刪除視圖的鏈接。 我想構建一個頁面,其中包含指向列表視圖的鏈接列表。 這是我如何做到的。

我在 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 %}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM