目前,我有6-7个应用程序在我的Django项目。在settings.py for STATICFILES_DIRS中,我需要指定所有应用程序中存在的资产目录、完整路径,这很麻烦,以防每次我需要在这里添加路径时都会增加应用程序。在我的所有应用程序中,不是只有一个设置可以指定资产文件夹和收集器命令来查找资产中的静态文件吗?
这就是我目前的情况:
STATICFILES_DIRS = [
BASE_DIR / "app1/templates/assets",
BASE_DIR / "app2/templates/assets",
BASE_DIR / "app3/templates/assets",
BASE_DIR / "app4/templates/assets",
BASE_DIR / "app5/templates/assets",
BASE_DIR / "app6/templates/assets",
]我所需要的是这样的东西,并且收藏品会去我所有的应用程序(1-6)寻找资产目录。
STATICFILES_DIRS = [
'templates/assets',
]有办法做同样的事吗?
发布于 2022-05-04 15:04:39
来自Django 4.0文档:https://docs.djangoproject.com/en/4.0/ref/contrib/staticfiles/
Django约定指出,我们可以在静态目录中的每个应用程序下拥有所有的静态文件。最好是在静态目录中创建另一个与project(projectname/appname/static/appname/all静态文件和文件夹同名的文件夹)
默认情况是查看STATICFILES_DIRS中定义的所有位置和INSTALLED_APPS设置指定的应用程序的“静态”目录。
注意:% static总是在settings.py、STATICFILES_DIRS中指定的STATIC_ROOT和每个应用程序中的静态目录下查找。index.html
<link rel="stylesheet" href="{% static 'app/css/bootstrap.min.css' %}" />
<link rel="stylesheet" href="{% static 'app/css/LineIcons.2.0.css' %}" />
<link rel="stylesheet" href="{% static 'app/css/animate.css' %}" />
<link rel="stylesheet" href="{% static 'app/css/tiny-slider.css' %}" />
<link rel="stylesheet" href="{% static 'app/css/glightbox.min.css' %}" />
<link rel="stylesheet" href="{% static 'app/css/main.css' %}" />settings.py
STATICFILES_DIRS = [
# specify other static directory where static files are stored n your environment.
# by default static folders under each app are always looked into and copied.
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static') # this is the folder where all static files are going to be stored after we run collectstatic command
STATIC_URL = '/static/' # this is the url from which static elements can be accessed在生产中:
常见的策略是从云存储提供商(如亚马逊的S3和/或CDN (内容交付网络))中提供静态文件。这让您忽略了为静态文件提供服务的问题,并且经常能够更快地加载网页(特别是在使用CDN时)。
将静态文件投入生产的基本大纲由两个步骤组成:当静态文件发生变化时运行收集器命令,然后安排将收集的静态文件目录(STATIC_ROOT)移动到静态文件服务器并提供服务。
但是在这里,我们使用apache服务器从同一台机器为静态文件提供服务。
每次更改静态文件时,都需要执行命令。
python manage.py collectstatic并在urls.py中指定静态url
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("app.urls")),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)由于所有静态文件都将由web服务器本身提供,所以我们需要指定配置文件中的位置。请注意,当apache服务器提供静态文件时,在生产中运行收集器命令是很重要的。它在配置文件(通常是STATIC_ROOT目录)中指定的位置查找静态文件。
/etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
#Serving static files
Alias /static/ /etc/myproject/static/
<Directory /etc/myproject/static>
Require all granted
</Directory>
<Directory /etc/myproject/myproject>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIDaemonProcess myproject python-path=/etc/myproject python-home=/etc/myprojectenv
WSGIProcessGroup myproject
WSGIScriptAlias / /etc/myproject/myproject/wsgi.py
</VirtualHost>https://stackoverflow.com/questions/72109511
复制相似问题