【发布时间】:2015-11-01 19:33:43
【问题描述】:
我一直在尝试找到一种将我的文档从本地文件夹显示到网页上的方法。我想知道这有两种方式:一种是使用 django 的 ListView,但在这种情况下我没有使用模型,所以我不确定它是否会起作用。我要解决的另一种方法是通过我制作的这个列表方法,但是我无法将正确的内容(标题、日期)放到网页上。它们显示在我创建的列表中,但不会翻译到网页。它只是一个空白页。这是我的代码:
views.py
import os, string, markdown, datetime
from P1config.settings import STATICBLOG_COMPILE_DIRECTORY,STATICBLOG_POST_DIRECTORY,STATICBLOG_STORAGE
def doclist(request):
mdown = markdown.Markdown(extensions = ['meta','extra', 'codehilite', PyEmbedMarkdown()])
posts = []
for item in os.listdir(STATICBLOG_POST_DIRECTORY):
if item.endswith('.md'):
continue
try:
with open(os.path.join(STATICBLOG_POST_DIRECTORY, item)) as fhandle:
content = fhandle.read() # (opening and reading the ENTIRE '.md' document)
mdown.convert(content) # (converting file from '.md' to ".html")
post = { 'file_name' : item }
if 'title' in mdown.Meta and len(mdown.Meta['title'][0]) > 0:
post['title'] = mdown.Meta['title'][0]
else:
post['title'] = string.capwords(item.replace('-', ' '))
if 'date' in mdown.Meta:
post['date'] = mdown.Meta['date'][0]
post['date']= datetime.datetime.strptime(post['date'], "%Y-%m-%d")
posts.append(post)
except:
pass
from operator import itemgetter
posts = sorted(posts, key=itemgetter('date'))
posts.reverse()
return render(
request,
'list.html',
{'post' : posts}
)
list.html
{% extends 'base.html' %}
{% block content %}
{% if post %}
{% for i in post %}
<h2>{{post.title}}</h2>
<p class="meta">{{post.date}}</p>
{% endfor %}
{% endif %}
{% endblock %}
还有我的 urls.py:
from django.conf.urls import include, url, patterns
urlpatterns = patterns('blog_static.views',
(r'^postlist/', 'list'),
)
我有两个问题:
- 你能找出我在这段代码中哪里出错了吗?
- 是否有任何替代方法可以做到这一点?这可能是从本地文件夹中列出文档的一种低效方式,因此我也愿意接受其他选项。
任何形式的帮助将不胜感激。谢谢!
【问题讨论】:
标签: python django python-3.x django-templates django-views