Skip to main content
 首页 » 编程设计

python之Django之静态文件夹不在基础项目中

2025年05月04日24lexus

我在将我的“静态”文件夹从基础“django_project”项目中移出时遇到了一些问题。根据我的经验,Django 会在基础项目中寻找“static”文件夹,但我觉得它很难看,我想将它移动到我所有其他 Django 应用程序旁边。

这是我当前的文件目录设置。

/home/django/django_project/ 
    /django_project/ 
    /myapplication/ 
    /templates/ 
    /static/ 

现在,'templates' 文件夹工作正常,我可以毫无困难地找到我所有的模板文件。但是,我找不到任何静态文件,静态设置总是让我上当。

这是我的“django_project”基础项目的 settings.py 文件。

... 
 
# Static files (CSS, JavaScript, Images) 
# https://docs.djangoproject.com/en/1.6/howto/static-files/ 
 
STATIC_URL = '/static/' 
 
# Go back one directory from this file and move into the 'static' folder 
STATICFILES_DIRS = ( 
    os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'static')), 
) 
 
# Template files (HTML) 
 
TEMPLATE_DIRS = ( 
    '/home/django/django_project/templates/', 
) 

谁能写出 STATIC_URL 或 STATICFILES_DIR 以便它指向我的“/home/django/django_project/static/”文件夹?提前谢谢你。

请您参考如下方法:

尝试这样的东西,它更干净。

STATIC_PATH = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'static')) 
 
STATIC_URL = '/static/' # You may find this is already defined as such. 
 
STATICFILES_DIRS = ( 
STATIC_PATH, 
) 

STATICFILE_DIRS - 这指定了本地磁盘上静态目录的位置

STATIC_URL - 这指定了从网络服务器访问静态媒体的 URL。

假设您的静态目录中有 dragontoothless.jpg 文件。要从您的 html 页面提供它,您可以使用类似这样的东西。

<img src="/static/dragontoothless.jpg" /> 

希望对您有所帮助!