【问题标题】:Django: Listing documents from a local folderDjango:列出本地文件夹中的文档
【发布时间】: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'), 
)

我有两个问题:

  1. 你能找出我在这段代码中哪里出错了吗?
  2. 是否有任何替代方法可以做到这一点?这可能是从本地文件夹中列出文档的一种低效方式,因此我也愿意接受其他选项。

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

【问题讨论】:

    标签: python django python-3.x django-templates django-views


    【解决方案1】:

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

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

    获取此视图的项目列表。这必须是一个可迭代的并且可能是一个查询集(其中将启用特定于查询集的行为)。

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

    class MyListView(generic.ListView):
        template_name = 'foobar.html'
    
        def get_queryset(self):
            return [1, 2, 3]
    

    您的示例有什么问题...事实上您在内部 for 循环中引用了 post,而不是您定义为实际帖子的 i

    这很令人困惑,因为您在模板上下文中将 python posts 变量重命名为 post,然后将其迭代为 i

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

    【讨论】:

    • 天哪...我不敢相信我忽略了这一点;但这就是我喜欢这个社区的原因:额外的一双眼睛。万分感谢。我设法修复了我的观点并列出了清单。 ...至于 ListView,我对它有点熟悉,但只是在模型的实现中。我几乎看不到它用于其他方式,而且我不完全确定我可以在模型之外使用它,但你的信息确实让我很好奇。我要看看我能用它们做什么。 Django docs,imo,并不完全有用 b/c 似乎他们希望您在阅读之前了解一定数量的信息。
    • @JellisHeRo 我发现 django 文档是文档质量的圣杯之一。我特别喜欢他们指出其他文档认为你知道的东西的能力。也就是说,CBV 文档需要一些知识才能继续。每个 CBV 都由列出的其他通用 mixin 组成 - 了解它们的工作原理是理解 CBV 的关键。
    【解决方案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 %}
    

    【讨论】:

    • 感谢您的回复。我完全错过了,所以感谢您发现错误!原来这是我的一大障碍。
    猜你喜欢
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多