首页 > 解决方案 > 在django中加载其他静态文件引用的静态文件

问题描述

在我的 Python Django 项目中,我有一个静态 html 文件 (map.html)。在这个 html 文件中引用了其他静态文件。像这样:

<!DOCTYPE html>
<html><head>    
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <script>L_PREFER_CANVAS = false; L_NO_TOUCH = false; L_DISABLE_3D = false;</script>
    <script src="mfiles/leaflet_002.js"></script>
    <script src="mfiles/jquery.js"></script>
    <script src="mfiles/bootstrap.js"></script>
    <script src="mfiles/leaflet.js"></script>
    <link rel="stylesheet" href="mfiles/leaflet.css">
    <link rel="stylesheet" href="mfiles/bootstrap.css">

...

使用 django 模板语言从模板文件 (index.html) 引用静态 html 文件,如下所示:

{% load static %}
<iframe src="{% static "map.html" %}" id="iframemap" style="top:0;left: 0;width:100%;height: 100%; position: absolute; border: none;">

问题是django找不到静态html文件(map.html)中引用的静态文件(mfiles/leaflet_002.js等),因为在这个html文件(map.html)中,django模板语言无法使用所以django 找不到这些文件的路径。

为了使我的架构干净,我展示了这个简单的图表:

django_template_file ----references----> map.html(静态,加载正常)----references----> mfiles/*.js 等(问题 django 看不到这些文件)

我如何告诉 django 也查看 m_app/static/mfiles/* 而不仅仅是 m_app/static/?

即使 m_app/static/mfiles/ 中的静态文件仅从位于 m_app/static/ 中的其他静态文件引用(并正确加载)?

文件结构的相关部分:

m_project
|______> m_app
    |______> __pychache__
    |______> migrations
    |______> static
            |______> m_files ("this folder is referenced in map.html and django doens't see it")
                |______> leaflet_002.js 
                |______> ...
            |______> map.html ("this is the static html file referenced from template index.html")
    |______> templates
        |______> m_app
            |______> index.html ("this is the template file I am talking about above")
    |______> __init__.py
    |______> admin.py
    |______> apps.py
    |______> models.py
    |______> tests.py
    |______> urls.py
    |______> views.py
|______> m_project
    |______> __pychache__
    |______> __init__.py
    |______> settings.py
    |______> urls.py
    |______> wsgi.py
|______> db.sqlite3
|______> manage.py

标签: pythondjango

解决方案


{% load staticfiles %}为什么你的里面没有index.html

# index.html
{% load staticfiles %}
<!DOCTYPE html>
<html><head>
    <script src='{% static "mfiles/leaflet_002.js" %} '></script>
    ...

# django settings
STATICFILES_DIRS = (
    os.path.join(SITE_ROOT, 'static'),
    os.path.join(SITE_ROOT, 'm_app', 'static'),
)

推荐阅读