Django本地文件列表

2024-10-01 04:53:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在试图找到一种方法来将我的文档从本地文件夹显示到网页上。我想从两个方面来考虑这个问题:一个是使用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'), 
)

我有两个问题:

  1. 你能找出我在这段代码中哪里出错了吗?在
  2. 我有没有别的办法可以做这个?这可能是一种从本地文件夹中列出文档的低效方法,因此我也可以选择其他方法。在

任何形式的帮助都将不胜感激。谢谢!在


Tags: 方法fromimport网页列表datetitleos
2条回答

post是dict对象的数组。所以

{% extends 'base.html' %}

{% block content %}
    {% if post %}
        {% for i in post %}
        <h2>{{i.title}}</h2>
        <p class="meta">{{i.date}}</p>
        {% endfor %}
    {% endif %}
{%  endblock %}

听起来您已经很熟悉了,可以使用ListView来执行此操作。您可以在没有模型的情况下使用ListView,如文档的各个部分所述(“不一定是查询集”):

https://docs.djangoproject.com/en/1.8/ref/class-based-views/mixins-multiple-object/#django.views.generic.list.MultipleObjectMixin.get_queryset

Get the list of items for this view. This must be an iterable and may be a queryset (in which queryset-specific behavior will be enabled).

因此,您应该能够执行以下操作:

class MyListView(generic.ListView):
    template_name = 'foobar.html'

    def get_queryset(self):
        return [1, 2, 3]

你的例子怎么了。。。事实上,您在内部for循环中引用post,而不是您定义为实际post的i。在

因为在模板上下文中将python posts变量重命名为post,然后以i的形式对其进行迭代。在

模板上下文中的posts只是一个列表,没有属性、键等,名为post.title。在

相关问题 更多 >