【发布时间】: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。