【问题标题】:django template import url tags is there a better way?django模板导入url标签有没有更好的方法?
【发布时间】:2018-03-13 22:09:09
【问题描述】:

我的目标是在页面中列出一些链接,我想知道是否有更好的方法来执行这行代码:

<a href={% url ''|add:app_name|add:':'|add:model_name|add:post_fix %}> {{ model_name }} </a>

这部分:''|add:app_name|add:':'|add:model_name|add:post_fix

-- 如果是这样,我的想法有什么缺陷,是 URL 名称,还是在模板中做的太多,或者其他什么?我应该在 view.py 中用 python 代码构建,如果可以,你能告诉我你将如何解决这个问题吗?

a_template.html

{% for model_name in list_model_names%}
    ....
    <a href={% url ''|add:app_name|add:':'|add:model_name|add:post_fix %}> {{ model_name }} </a>
    ....
{% endfor %}

url.py

from django.conf.urls import url

from . import views

app_name = 'app'
urlpatterns = [
url(r'^stone/$, view.....as_view(), name='stone_index'),
url(r'^cloud/$', view.....as_view(), name='cloud_index'),
]

views.py

from django.shortcuts import render_to_response
from django.views import View
from app.models import (Stone, Cloud)
class ThisView(View):
   template_name = 'app/a_template.html'
   models = [Stone, Cloud]
   model_names = [model._meta.model_name for model in models]
   app_name = 'app'
   post_fix = '_index'

   dict_to_template = {'app_name': app_name,
                    'list_model_name': model_names,
                    'post_fix': post_fix}

   def get(self, *args, **kwargs):
       return render_to_response(self.template_name, self.dict_to_template)

感谢您的宝贵时间。

【问题讨论】:

  • render_to_response 已过时。请改用render

标签: django django-templates


【解决方案1】:

将模板中的 url 颠倒过来会更整洁

from django.urls import reverse . # Django 1.9+
# from django.core.urlresolvers import reverse # Django < 1.9

model_names = [model._meta.model_name for model in models]
app_name = 'app'
post_fix = '_index'
urls = [reverse('%s:%s%s' % (app_name, model, post_fix)) for model in model_names

然后将模型名称和 url 压缩在一起,并将它们包含在模板上下文中:

models_and_urls = zip(model_names, urls)
dict_to_template = {'models_and_urls: models_and_urls}

然后您可以遍历模板中的模型名称和 url。

{% for model_name, url in models_and_urls %}
    ....
    <a href="{{ url }}"> {{ model_name }} </a>
    ....
{% endfor %}

【讨论】:

    猜你喜欢
    • 2010-12-27
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 2011-03-27
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多