列出 Django 模板中的目录文件内容

发布于 2024-10-15 18:42:58 字数 1679 浏览 1 评论 0原文

我刚刚学习 Python 和姜戈。 (感谢在这里做出贡献的每个人 - 这是一个无价的资源!)

我遇到的一件看似基本的事情是将一个简单的静态文件列表(比如我的服务器上单个存储库目录的内容)渲染为可下载链接列表。这是否安全是另一个问题,但假设我想这样做......

这篇文章帮助我走向正确的方向: Python 目录列表返回到 Django 模板

此代码片段输出文件名'myfiles' 如果从提示符运行:

path= os.path.dirname(os.path.abspath(__file__))  
myfiles = os.path.join(path, 'myfiles')  
os.chdir(myfiles)  
for files in os.listdir("."):
     print files  

但是如何将这些文件传递到 Django 模板并生成链接列表?我想我可能必须创建某种Python字典/元组以使其可迭代,将其作为模板变量传递并在for循环中渲染它?

我是否必须在 urls.py 文件中添加一个条目才能使其工作?像这样的东西吗?

(r'^myfiles/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.dirname(__file__), 'myfiles'), 'show_indexes': True}),

感谢您的帮助!我只是在学习,我无法真正弄清楚如何从现有的在线代码片段中做到这一点。

编辑:这是我在views.py中得到的:(你会从'\\'注意到我在Windows系统上)

def myfiles_page(request):
    path = os.path.dirname(os.path.abspath(__file__))
    myfiles = os.path.join(path, 'myfiles\\')
    os.chdir(myfiles)
    x = 0
    d = {}
    for file in os.listdir("."):
        d[x] = (myfiles + file)
        x = x + 1

    variables = RequestContext(request, {
    'user' : request.user,
    'filedict' : d,
    })
    return render_to_response('myfiles_page.html', variables)

这就是我试图让它在模板中显示的方式: (根据 Django 文档

{% for key, value in filedict %}
    {{ key }}: {{ value }}
{% endfor %}

但是 'filedict'模板中仍然没有显示任何内容。有什么想法吗?

I'm just learning Python & Django. (Thanks to everyone who contributes here -- it's been an invaluable resource!)

One seemingly basic thing that I'm having trouble with is rendering a simple list of static files (say the contents of a single repository directory on my server) as a list of downloadable links. Whether this is secure or not is another question, but suppose I want to do it...

This post helped steer me in the right direction:
Python directory list returned to Django template

This code snippet outputs the filenames in 'myfiles' if run from a prompt:

path= os.path.dirname(os.path.abspath(__file__))  
myfiles = os.path.join(path, 'myfiles')  
os.chdir(myfiles)  
for files in os.listdir("."):
     print files  

But how do I pass these files to a Django template and generate a list of links? I think I may have to create a Python dictionary/tuple of some sort to make it iterable, pass it as a template variable and render it in a for loop?

Do I have to add an entry to my urls.py file to make this work? Something like this?

(r'^myfiles/(?P<path>.*)

Thanks for your help! I'm just learning and I couldn't really figure out how to do this from existing code snippets online.

EDIT: This is what I've got in my views.py: (you'll notice from the '\\' that I'm on a Windows system)

def myfiles_page(request):
    path = os.path.dirname(os.path.abspath(__file__))
    myfiles = os.path.join(path, 'myfiles\\')
    os.chdir(myfiles)
    x = 0
    d = {}
    for file in os.listdir("."):
        d[x] = (myfiles + file)
        x = x + 1

    variables = RequestContext(request, {
    'user' : request.user,
    'filedict' : d,
    })
    return render_to_response('myfiles_page.html', variables)

This is how I was trying to get it to display in a template:
(according to the Django documentation)

{% for key, value in filedict %}
    {{ key }}: {{ value }}
{% endfor %}

But 'filedict' is still not displaying anything in the template. Any ideas?

, 'django.views.static.serve', {'document_root': os.path.join(os.path.dirname(__file__), 'myfiles'), 'show_indexes': True}),

Thanks for your help! I'm just learning and I couldn't really figure out how to do this from existing code snippets online.

EDIT: This is what I've got in my views.py: (you'll notice from the '\\' that I'm on a Windows system)

This is how I was trying to get it to display in a template:
(according to the Django documentation)

But 'filedict' is still not displaying anything in the template. Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一江春梦 2024-10-22 18:42:58

我认为,事情并非如此。

您可能需要在views.py 中创建自己的函数 - 请参阅教程。

该函数会将 os.listdir 中的文件列表获取到列表中。

将上下文中的列表传递给模板,并使用您编写的模板执行 render_to_response - 请参阅教程。

在模板中,它类似于:

{% for file in filelist %}
  {{ file }}
{% endfor %}

您可以将上下文中的任何内容传递给模板。您可能还想传递带有 URL 的文件扩展列表 - 字典列表,其中每个字典都有一个名称和一个 url。那么你的模板是:

{% for file in filelist %}
  <a href="{{file.url}}">{{ file.name }}</a>
{% endfor %}

BIG FAT SECURITY WARNING

不要让用户通过在 URL 中放置路径来浏览文件,至少在没有真正检查他们不能执行 /myfiles/../../ 之类的操作的情况下。 notmyfiles/secret.txt 并通过在向上的路径中粘贴点来查看其他人的文件。

如果你不明白这一点,那么你可能不应该在除了一个你不介意被撕成碎片的玩具系统之外的任何东西上编写这个代码!

Something very much not like that, I reckon.

You'll probably need to create a function of your own inside views.py - see tutorial.

That function will get the file list from os.listdir into a list.

Pass that list in the context to a template and do render_to_response with a template you've written - see tutorial.

In the template, its then something like:

{% for file in filelist %}
  {{ file }}
{% endfor %}

You can pass anything in the context to a template. You might want to pass an augmented list of files with URLs too - a list of dicts, where each dict has a name and a url. Then your template is:

{% for file in filelist %}
  <a href="{{file.url}}">{{ file.name }}</a>
{% endfor %}

BIG FAT SECURITY WARNING

Don't let users browse files by letting them put a path in a URL, at least not without really really checking that they can't do stuff like /myfiles/../../notmyfiles/secret.txt and see other peoples files just by sticking dot-dots in the path to go upwards.

If you dont understand that, then you probably shouldn't be coding this up on anything but a toy system that you don't mind being ripped to pieces!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文