简体   繁体   English

在Django views.py中引用文件

[英]Referencing file in Django views.py

I am building a Django web interface (overkill - I know!) for a few small python functions. 我正在为一些小的python函数构建Django Web界面(过度杀手-我知道!)。 One of these transforms a txt file stored in Django root. 其中之一转换存储在Django根目录中的txt文件。 Well it aims to. 好吧,它的目标是。

I have the following setup in a few places: 我在一些地方进行了以下设置:

with open('file.csv','r') as source:
...

However, without setting the entire directory on my machine (eg /home/...), it cannot find the file. 但是,如果未在我的计算机上设置整个目录(例如/ home / ...),则无法找到该文件。 I have tried putting this in the Static directory (as ideally I would like people to be able to download the file at a later stage) but same problem. 我尝试将其放置在静态目录中(理想情况下,我希望人们可以在以后下载文件),但存在相同的问题。

How do you work with files within Django? 您如何在Django中处理文件? What is best practice to solve the above allowing someone to download it later? 解决上述问题的最佳做法是什么,以便以后允许他人下载?

If you only need the path: 如果只需要路径:

import os
from django.conf import settings

file_path = os.path.join(settings.STATIC_ROOT, 'file.txt')

with open(file_path, 'r') as source:
    # do stuff
  • Please notice that you need to put your file in a directory like this: my_app/static/my_app/file.txt 请注意,您需要将文件放在这样的目录中:my_app / static / my_app / file.txt

for more information you can refer to Django docs . 有关更多信息,请参考Django 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM