我正在用Django做一个具有以下结构的项目:
/project
/cv
/static
/configuration
configuration.json
因此,一个包含一个应用程序和静态文件夹中的config.json文件的项目。
我的设置.py(最重要的设置(:
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"cv",
]
STATIC_URL = "/static/"
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(BASE_DIR, "cv/static")
在我看来,我使用static((函数来检索静态文件
def index(request):
file_path = static("configuration/configuration.json")
with open(file_path) as f:
configuration = json.loads(f.read())
return render(request, "index.html", configuration)
但它一直给我错误:
没有这样的文件或目录:'/static/configuration/configuration.json'
我可以通过显式解析索引函数的路径字符串来修复它:
def index(request):
file_path = "./cv/static/configuration/configuration.json"
with open(file_path) as f:
configuration = json.loads(f.read())
return render(request, "index.html", configuration)
但是如何使用static((函数呢?static((函数使用staticurl变量,但无论我如何调整它,它都会不断给我一个类似的错误。
有人知道我在这里做错了什么吗?
static()
函数将返回可以访问文件的URL,您不需要它,您需要获得文件系统上文件的路径。
连接settings.STATIC_ROOT
和文件以获取文件系统上文件的路径
def index(request):
file_path = os.path.join(settings.STATIC_ROOT, "configuration/configuration.json")
with open(file_path) as f:
configuration = json.loads(f.read())
return render(request, "index.html", configuration)