0

我想创建一个 TemplateView 来显示特定目录下的所有模板。

所以例如我有

/staticpages/about-me.html
/staticpages/about-you.html
/staticpages/about-us.html

...

(还有很多)

在我的 urls.py 我有..

url(r'^(?P<page_name>[-\w]+)/$', StaticPageView.as_view()),

..

在我的views.py中我有

class StaticPageView(TemplateView):
    def get_template_names(self):
        return 'staticpages/%s' % self.kwargs['page_name']

但是,如果有人访问 url /staticpages/blahblah.html (不存在),它会被此视图接受并生成模板未找到错误。如果找不到模板,如何重定向到 404?

或者有没有更好的方法来做到这一点?

4

1 回答 1

0

您可以考虑使用将为您提供模板目录的项目设置。然后,您可以使用 os.listdir ( http://docs.python.org/library/os.html#os.listdir ) 列出该目录中存在的所有模板。这是如何实现它的。(以下代码未经测试..只是给你一个想法)

模板列表可以这样显示:

# views.py
import os
from django.conf import settings

template_directory = os.path.join(settings.TEMPLATE_DIRS,'sub_directory')
templates = os.listdir(template_directory)
return render_to_response('template_list.html')

对应的模板文件..

# template_list.html
<ul>
{% for template in templates %}
  <li> <a href="/{{template}}"> {{template.filename}} </a> </li>
{% endfor %}
</ul>

希望有帮助..

于 2012-02-15T06:20:26.567 回答