在 Django 中创建模板子目录的视图
我想创建一个 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 吗?
或者有更好的方法来做到这一点吗?
I'd like to create a TemplateView that displays all templates under a specific directory.
So for example I have
/staticpages/about-me.html
/staticpages/about-you.html
/staticpages/about-us.html
...
(many more)
In my urls.py i have
..
url(r'^(?P<page_name>[-\w]+)/
..
In my views.py i have
class StaticPageView(TemplateView):
def get_template_names(self):
return 'staticpages/%s' % self.kwargs['page_name']
However if someone goes to the url /staticpages/blahblah.html (which doesn't exist), It gets accepted by this view and a template not found error is generated. Howe can I redirect to a 404 if template not found?
Or alternately is there a better way of doing this?
, StaticPageView.as_view()),
..
In my views.py i have
However if someone goes to the url /staticpages/blahblah.html (which doesn't exist), It gets accepted by this view and a template not found error is generated. Howe can I redirect to a 404 if template not found?
Or alternately is there a better way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以考虑使用项目设置,它将为您提供模板目录。然后,您可以使用 os.listdir ( http://docs.python.org/ library/os.html#os.listdir )列出该目录中存在的所有模板。以下是实现这一目标的方法。 (以下代码未经测试..只是为了给您一个想法)
模板列表可以这样显示:
相应的模板文件..
希望有帮助..
You can consider using the project settings which will give you the templates directory. You can then use the os.listdir ( http://docs.python.org/library/os.html#os.listdir ) to list all the templates present in that directory. Here is how one can achieve it. (The following code is not tested.. it is just to give you an idea)
The list of templates can be displayed like this:
The corresponding template file..
Hope that helps..