【问题标题】:Create a view to a subdirectory of templates in Django在 Django 中创建模板子目录的视图
【发布时间】:2012-03-06 10:59:46
【问题描述】:

我想创建一个 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?

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

【问题讨论】:

    标签: django django-templates django-class-based-views


    【解决方案1】:

    您可以考虑使用将为您提供模板目录的项目设置。然后,您可以使用 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>
    

    希望对您有所帮助..

    【讨论】:

      猜你喜欢
      • 2020-07-15
      • 2017-12-18
      • 2011-12-15
      • 2014-03-11
      • 1970-01-01
      • 1970-01-01
      • 2013-07-19
      • 2019-12-06
      • 1970-01-01
      相关资源
      最近更新 更多