我一直在试图找到一种方法来将我的文档从本地文件夹显示到网页上。我想从两个方面来考虑这个问题:一个是使用django的ListView,但是在本例中我没有使用模型,所以我不确定它是否能工作。另一种方法是通过我制作的列表方法,但是我很难在网页上找到合适的内容(标题、日期)。它们出现在我创建的列表中,但不会翻译到网页上。只是一页空白。我的代码是:
视图.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}
)
列表.html
^{pr2}$我的网址.py:
from django.conf.urls import include, url, patterns
urlpatterns = patterns('blog_static.views',
(r'^postlist/', 'list'),
)
我有两个问题:
任何形式的帮助都将不胜感激。谢谢!在
post
是dict对象的数组。所以听起来您已经很熟悉了,可以使用
ListView
来执行此操作。您可以在没有模型的情况下使用ListView
,如文档的各个部分所述(“不一定是查询集”):https://docs.djangoproject.com/en/1.8/ref/class-based-views/mixins-multiple-object/#django.views.generic.list.MultipleObjectMixin.get_queryset
因此,您应该能够执行以下操作:
你的例子怎么了。。。事实上,您在内部for循环中引用
post
,而不是您定义为实际post的i
。在因为在模板上下文中将python
posts
变量重命名为post
,然后以i
的形式对其进行迭代。在模板上下文中的
posts
只是一个列表,没有属性、键等,名为post.title
。在相关问题 更多 >
编程相关推荐