Django 中的 STATIC_ROOT 与 STATIC_URL

发布于 2024-12-23 17:11:54 字数 1071 浏览 4 评论 0原文

我对静态根感到困惑,想澄清一下。

要在 Django 中提供静态文件,settings.pyurls.py 中应包含以下内容:

import os
PROJECT_DIR=os.path.dirname(__file__)

1. 应收集静态文件的目录的绝对路径

STATIC_ROOT= os.path.join(PROJECT_DIR,'static_media/')

2.静态文件的 URL 前缀

STATIC_URL = '/static/'

3. 静态文件的其他位置

STATICFILES_DIRS = ( os.path.join(PROJECT_DIR,'static/'),)

...以及在 urls.py 中的以下几行:

from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += patterns('', (
    r'^static/(?P<path>.*)$',
    'django.views.static.serve',
    {'document_root': settings.STATIC_ROOT}
))

4. 我们还使用 python manage.pycollectstatic

问题:

  1. 有人可以向我解释一下工作流程吗:理想情况下事情应该怎样做。截至目前,我将上述代码片段复制/粘贴到指定位置,并继续在静态目录中创建新文件,它就可以工作了。然而,在我的 settings.STATIC_ROOT 中,我指向了另一个目录。

  2. 如果有人能够解释每个设置的工作流程:如何收集和管理文件,以及遵循什么是好的做法,那就太好了。

谢谢。

I am confused by static root and want to clarify things.

To serve static files in Django, the following should be in settings.py and urls.py:

import os
PROJECT_DIR=os.path.dirname(__file__)

1. Absolute path to the directory in which static files should be collected

STATIC_ROOT= os.path.join(PROJECT_DIR,'static_media/')

2. URL prefix for static files

STATIC_URL = '/static/'

3. Additional locations for static files

STATICFILES_DIRS = ( os.path.join(PROJECT_DIR,'static/'),)

...and in urls.py the following lines:

from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += patterns('', (
    r'^static/(?P<path>.*)

4. We also use python manage.py collectstatic

Questions:

  1. Could anyone please explain the workflow to me: how should things ideally be done. As of now, I copy/paste the above code snippets into their designated locations and continue making new files in the static directory and it works. In my settings.STATIC_ROOT, however, I have pointed to a different directory.

  2. It would be great if someone could explain the workflow of each setting: how files are collected and managed, and what would be a good practice to follow.

Thanks.

, 'django.views.static.serve', {'document_root': settings.STATIC_ROOT} ))

4. We also use python manage.py collectstatic

Questions:

  1. Could anyone please explain the workflow to me: how should things ideally be done. As of now, I copy/paste the above code snippets into their designated locations and continue making new files in the static directory and it works. In my settings.STATIC_ROOT, however, I have pointed to a different directory.

  2. It would be great if someone could explain the workflow of each setting: how files are collected and managed, and what would be a good practice to follow.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

似狗非友 2024-12-30 17:11:54

静态根

./manage.pycollectstatic 将收集用于部署的静态文件的目录的绝对路径。
示例:STATIC_ROOT="/var/www/example.com/static/"

现在命令 ./manage.pycollectstatic 将复制所有将静态文件(即应用程序中的静态文件夹中、所有路径中的静态文件)复制到目录 /var/www/example.com/static/ 中。现在你只需要在 apache 或 nginx 等上提供这个目录。

STATIC_URL

提供STATIC_ROOT目录中的静态文件的URL(由Apache或nginx等)。
示例:/static/http://static.example.com/

如果您设置 STATIC_URL = 'http:// static.example.com/',那么您必须通过以下方式提供 STATIC_ROOT 文件夹(即 "/var/www/example.com/static/") url 处的 apache 或 nginx 'http://static.example.com/'(以便您可以引用静态文件'/var/www/example.com/static/jquery.js''http://static.example.com/jquery.js')

现在在您的 django-templates 中,您可以通过以下方式引用它:

{% load static %}
<script src="{% static "jquery.js" %}"></script>

它将呈现:

<script src="http://static.example.com/jquery.js"></script>

STATIC_ROOT

The absolute path to the directory where ./manage.py collectstatic will collect static files for deployment.
Example: STATIC_ROOT="/var/www/example.com/static/"

now the command ./manage.py collectstatic will copy all the static files(ie in static folder in your apps, static files in all paths) to the directory /var/www/example.com/static/. now you only need to serve this directory on apache or nginx..etc.

STATIC_URL

The URL of which the static files in STATIC_ROOT directory are served(by Apache or nginx..etc).
Example: /static/ or http://static.example.com/

If you set STATIC_URL = 'http://static.example.com/', then you must serve the STATIC_ROOT folder (ie "/var/www/example.com/static/") by apache or nginx at url 'http://static.example.com/'(so that you can refer the static file '/var/www/example.com/static/jquery.js' with 'http://static.example.com/jquery.js')

Now in your django-templates, you can refer it by:

{% load static %}
<script src="{% static "jquery.js" %}"></script>

which will render:

<script src="http://static.example.com/jquery.js"></script>
像极了他 2024-12-30 17:11:54

STATICFILES_DIRS:您可以在此处保留项目的静态文件,例如模板使用的文件。

STATIC_ROOT:将其留空,当您执行manage.pycollectstatic时,它将搜索系统上的所有静态文件并将它们移动到此处。您的静态文件服务器应该映射到该文件夹​​,无论它位于何处。运行collectstatic后检查一下,你会发现django已经构建了目录结构。

--------编辑----------------

正如@DarkCygnus所指出的,STATIC_ROOT应该指向文件系统上的一个目录,该文件夹应该是空的,因为它会由 Django 填充。

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

STATIC_ROOT = '/opt/web/project/static_files'

--------结束编辑 -----------------

STATIC_URL: '/static/' 通常没问题,它只是静态文件的前缀。

STATICFILES_DIRS: You can keep the static files for your project here e.g. the ones used by your templates.

STATIC_ROOT: leave this empty, when you do manage.py collectstatic, it will search for all the static files on your system and move them here. Your static file server is supposed to be mapped to this folder wherever it is located. Check it after running collectstatic and you'll find the directory structure django has built.

--------Edit----------------

As pointed out by @DarkCygnus, STATIC_ROOT should point at a directory on your filesystem, the folder should be empty since it will be populated by Django.

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

or

STATIC_ROOT = '/opt/web/project/static_files'

--------End Edit -----------------

STATIC_URL: '/static/' is usually fine, it's just a prefix for static files.

骑趴 2024-12-30 17:11:54

2023 年 8 月更新:

首先,我解释一下 STATIC_ROOT,然后 [STATIC_URL2

STATIC_ROOT 可以设置一个文件夹路径,与下面的命令一起使用,将 Django 项目中的 apps 和 admin 的静态文件收集到该文件夹​​路径中。 *STATIC_ROOT 永远不会影响 STATIC_URL

python manage.py collectstatic 

并且 STATIC_ROOT 仅适用于生产模式,即 DEBUG = False 如下所示:

# "core/settings.py"

DEBUG = False // Production Mode

现在,我们有一个包含静态文件的 django 项目core.js 位于 core 文件夹中,其中 settings.py 位于 myapp 中code> 文件夹,它是应用程序,如下所示:

在此处输入图像描述

css字体、< venv 文件夹中 admin 文件夹中的 code>img 和 js 文件夹如下所示。 *我为此 django 项目使用名为 venv 的虚拟环境,因此 admin 的静态文件位于其中,并且 admin 文件夹的相对路径为 venv/lib/ python3.8/site-packages/django/contrib/admin/static/admin/:

<图像src="https://i.sstatic.net/ThKL0.png" alt="在此处输入图像描述">

然后,我们设置 BASE_DIR / 'static/' ,即 <在我的例子中,Windows 上的 code>C:\Users\kai\django-project\static 为 STATIC_ROOT。此外,我们设置 DEBUG = False 因为 STATIC_ROOT 仅适用于生产模式,正如我之前所说:

# "core/settings.py"

DEBUG = False // Production Mode

STATIC_ROOT = BASE_DIR / 'static/' # Here
STATIC_URL = 'static/'

现在,我们运行以下命令:

python manage.py collectstatic 

然后、 static 文件夹已创建,并且 cssfontsimgjs 文件夹位于admin 文件夹** 和myapp 文件夹中的 myapp.css 被收集到 static 文件夹中,如下所示,但我们可以看到,core.jscore 文件夹中的 > 不会收集到 static 文件夹中,如下所示,因为正如我之前所说,命令 python manage.pycollectstatic 收集静态文件来自 django 项目中的应用程序和管理,但 core 文件夹其中有 settings.py 不是应用程序和管理员。这就是为什么 core 文件夹中的 core.js 没有收集到 static 文件夹中:

在此处输入图像描述

但是,有一种方法收集将 core 文件夹中的 core.js 复制到 static 文件夹中。为此,我们需要在 Windows 上设置 BASE_DIR / 'core/static/' ,即 C:\Users\kai\django-project\core\static案例为 STATICFILES_DIRSsettings.py 如下所示:

# "core/settings.py"

DEBUG = False

STATICFILES_DIRS = [ # Here
    BASE_DIR / 'core/static/'
]

STATIC_ROOT = BASE_DIR / 'static/'
STATIC_URL = 'static/'

或者,我们需要将 core 设置为 INSTALLED_APPS in settings.py 如下所示:

# "core/settings.py"

DEBUG = False

INSTALLED_APPS = [
    'core', # Here
]

现在,我们再次运行以下命令:

python manage.py collectstatic 

然后,输入 yes然后按 Enter 覆盖现有 static 文件夹:

您已请求在目标位置收集静态文件
按照您的设置中的指定:

C:\Users\kai\django-project\static

这将覆盖现有文件!您确定要这样做吗?

输入“是”继续,或输入“否”取消:是

现在,core 文件夹中的 core.js 被收集到 static 文件夹中,如下所示如下所示:

“输入图像描述此处"

接下来,我解释一下 STATIC_URL

STATIC_URL 可以将静态文件 URL 的前目录部分设置在静态文件 URL 的主机部分和文件部分之间,如下所示。 *STATIC_URL 永远不会影响 STATIC_ROOT

       |     Host      |   Directory    |  File  |
       |               |Front |  Back   |        |
        <-------------> <----> <-------> <------>      
https://www.example.com/static/admin/css/base.css

例如,我们在 中将 'static/' 设置为 STATIC_URL settings.py 如下所示。 *STATIC_URL开发模式(即 DEBUG = True)和生产模式(即 DEBUG = False

# "core/settings.py"

DEBUG = False

STATICFILES_DIRS = [
    BASE_DIR / 'core/static/'
]

STATIC_ROOT = BASE_DIR / 'static/'
STATIC_URL = 'static/' # Here

然后,打开 Django Admin:

在此处输入图像描述

然后,按F12打开开发者工具Sources检查当前打开的Django管理页面使用的资源,并且有我们刚刚收集到static文件夹中的管理静态文件:

在此处输入图像描述

然后,将鼠标悬停在 css 中的 base.css 以检查 URL:

在此处输入图像描述

正如我们所见,我们可以设置前面的目录部分 static

                       Here  
                     <------>
http://localhost:8000/static/admin/css/base.css

并且,下面的 URL 是 www.example.comhttps

                         Here
               <------>
https://www.example.com/static/admin/css/base.css

并且,我们可以更改前面的目录部分 静态hello/world

因此,只需将 STATIC_URL'static/' 更改为 'hello/world/' ,如下所示:

# "core/settings.py"

DEBUG = False

STATICFILES_DIRS = [
    BASE_DIR / 'core/static/'
]

STATIC_ROOT = BASE_DIR / 'static/'
STATIC_URL = 'hello/world/' # Here

然后,刷新 Django 管理页面:

输入图片描述这里

然后,将前面目录部分static改为hello/world,如下所示:

                         Here  
                     <----------->
http://localhost:8000/hello/world/admin/css/base.css

Aug, 2023 Update:

First of all, I explain about STATIC_ROOT, then [STATIC_URL2.

<STATIC_ROOT>

STATIC_ROOT can set a folder path and be used with the command below which collects the static files of the apps and admin in a Django project into the folder path. *STATIC_ROOT never ever influence to STATIC_URL:

python manage.py collectstatic 

And STATIC_ROOT only works in Production Mode which is DEBUG = False as shown below:

# "core/settings.py"

DEBUG = False // Production Mode

Now, we have a django project with the static files core.js in core folder where settings.py is and myapp.css in myapp folder which is an app as shown below:

enter image description here

And css, fonts, img and js folders in admin folder in venv folder as shown below. *I use the virtual environment named venv for this django project so the static files for admin is in it and the relative path to admin folder is venv/lib/python3.8/site-packages/django/contrib/admin/static/admin/:

enter image description here

Then, we set BASE_DIR / 'static/' which is C:\Users\kai\django-project\static on Windows in my case to STATIC_ROOT. In addition, we set DEBUG = False because STATIC_ROOT only works in Production Mode as I said before:

# "core/settings.py"

DEBUG = False // Production Mode

STATIC_ROOT = BASE_DIR / 'static/' # Here
STATIC_URL = 'static/'

Now, we run the command below:

python manage.py collectstatic 

Then, static folder is created and css, fonts, img and js folders in admin folder** and myapp.css in myapp folder are collected into static folder as shown below but as we can see, core.js in core folder is not collected into static folder as shown below because as I said before, the command python manage.py collectstatic collects static files from the apps and admin in a django project but core folder which has settings.py is not an app and admin. That's why core.js in core folder is not collected into static folder:

enter image description here

But, there is a way to collect core.js in core folder into static folder. To do that, we need to set BASE_DIR / 'core/static/' which is C:\Users\kai\django-project\core\static on Windows in my case to STATICFILES_DIRS in settings.py as shown below:

# "core/settings.py"

DEBUG = False

STATICFILES_DIRS = [ # Here
    BASE_DIR / 'core/static/'
]

STATIC_ROOT = BASE_DIR / 'static/'
STATIC_URL = 'static/'

Or, we need to set core to INSTALLED_APPS in settings.py as shown below:

# "core/settings.py"

DEBUG = False

INSTALLED_APPS = [
    'core', # Here
]

Now again, we run the command below:

python manage.py collectstatic 

Then, input yes then press Enter to overwrite the existing static folder:

You have requested to collect static files at the destination location
as specified in your settings:

C:\Users\kai\django-project\static

This will overwrite existing files! Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel: yes

Now, core.js in core folder is collected into static folder as shown below:

enter image description here

<STATIC_URL>

Next, I explain about STATIC_URL.

STATIC_URL can set the front directory part of static file URL between the host part and the file part of static file URL as shown below. *STATIC_URL never ever influence STATIC_ROOT:

       |     Host      |   Directory    |  File  |
       |               |Front |  Back   |        |
        <-------------> <----> <-------> <------>      
https://www.example.com/static/admin/css/base.css

For example, we set 'static/' to STATIC_URL in settings.py as shown below. *STATIC_URL works in both Development Mode which is DEBUG = True and Production Mode which is DEBUG = False:

# "core/settings.py"

DEBUG = False

STATICFILES_DIRS = [
    BASE_DIR / 'core/static/'
]

STATIC_ROOT = BASE_DIR / 'static/'
STATIC_URL = 'static/' # Here

Then, open Django Admin:

enter image description here

Then, press F12 to open Developer Tools to check the resources used for the currently opened Django Admin page from Sources and there are the static files for admin which we have just collected into static folder:

enter image description here

Then, hover base.css in css to check the URL:

enter image description here

As we can see, we could set the front directory part static:

                       Here  
                     <------>
http://localhost:8000/static/admin/css/base.css

And, this URL below is in this case of www.example.com with https:

                         Here
               <------>
https://www.example.com/static/admin/css/base.css

And, we can change the front directory part static to hello/world.

So, just change STATIC_URL from 'static/' to 'hello/world/' as shown below:

# "core/settings.py"

DEBUG = False

STATICFILES_DIRS = [
    BASE_DIR / 'core/static/'
]

STATIC_ROOT = BASE_DIR / 'static/'
STATIC_URL = 'hello/world/' # Here

Then, refresh the Django Admin page:

enter image description here

Then, the front directory part static is changed to hello/world as shown below:

                         Here  
                     <----------->
http://localhost:8000/hello/world/admin/css/base.css
谁的年少不轻狂 2024-12-30 17:11:54

上面的所有答案都有帮助,但没有解决我的问题。在我的生产文件中,我的 STATIC_URL 是 https:///static 并且我在我的 dev settings.py 文件中使用了相同的 STATIC_URL。

这会导致 django/conf/urls/static.py 中出现静默失败。

测试 elif 不是 settings.DEBUG 或前缀中的 '://':
选取 URL 中的“//”,但不添加静态 URL 模式,导致找不到静态文件。

如果 Django 吐出一条错误消息,指出您不能使用 http(s)://DEBUG = True

我必须将 STATIC_URL 更改为'/静止的/'

All the answers above are helpful but none solved my issue. In my production file, my STATIC_URL was https://<URL>/static and I used the same STATIC_URL in my dev settings.py file.

This causes a silent failure in django/conf/urls/static.py.

The test elif not settings.DEBUG or '://' in prefix:
picks up the '//' in the URL and does not add the static URL pattern, causing no static files to be found.

It would be thoughtful if Django spit out an error message stating you can't use a http(s):// with DEBUG = True

I had to change STATIC_URL to be '/static/'

那小子欠揍 2024-12-30 17:11:54

Django 3.1+ 之后,目录路径的配置略有变化,但概念当然是相同的。

STATICFILES_DIRS

STATICFILES_DIRS = [
    BASE_DIR / 'static',
    BASE_DIR / 'app_1/static',
    BASE_DIR / 'app_2/static',
]

顾名思义,它是一个目录列表。它用于为静态文件指定多个目录。对于应用程序的可重用性而言最有用。每个应用程序都有其独立的目录,而不是为所有静态文件提供一个目录。就像每个单独应用程序的模板一样。

配置应用程序的静态文件目录:

=> my_app
    => static
        => my_app
            => css
            => js

在开发模式下,使用命令python manage.py runserver,Django使用STATICFILES_FINDERS设置搜索静态文件。默认情况下,它尝试在 STATICFILES_DIRS 设置中列出的文件夹中查找请求的静态文件。如果失败,Django 会尝试使用 django.contrib.staticfiles.finders.AppDirectoriesFinder 来查找文件,该文件会在项目中每个已安装应用程序的静态文件夹中查找。

STATIC_ROOT

STATIC_ROOT = BASE_DIR / 'static'

它是 python manage.pycollectstatic 收集用于部署的静态文件的目录的绝对路径。示例:

/var/www/example.com/static/"

对于开发来说,没有必要配置STATIC_ROOT,但对于生产来说却极其重要。这是Nginx、Apache服务器访问网站静态文件时要考虑的路径。

STATIC_URL

引用位于 STATIC_ROOT 中的静态文件时使用的 URL。示例:“static/”或“http://static.example.com/”

STATIC_URL = '/static/'

现在,假设我决定配置 STATIC_URL='/asset/',那么我需要更改 STATIC_ROOT=BASE_DIR / 'asset' 并且我的目录名称也应该是 asset

参考:

https://docs.djangoproject.com/en/4.0/ref /contrib/staticfiles/

After Django 3.1+, There is a slight change in the configuration of the directory paths, but the concepts are the same, of course.

STATICFILES_DIRS

STATICFILES_DIRS = [
    BASE_DIR / 'static',
    BASE_DIR / 'app_1/static',
    BASE_DIR / 'app_2/static',
]

As the name suggests, it is a list of directories. It is used for specifying more than one directory for static files. Most useful for the sake of the reusability of an app. Instead of having one directory for all the static files, each app has its independent directory. Just like templates for each individual app.

To configure static files directory of an app:

=> my_app
    => static
        => my_app
            => css
            => js

In development mode, with the command python manage.py runserver, Django searches for static files using the STATICFILES_FINDERS setting. By default, it tries to find the requested static file in folders listed in the STATICFILES_DIRS setting. In case of failure, Django tries to find the file using django.contrib.staticfiles.finders.AppDirectoriesFinder, which looks in the static folder of every installed application in the project.

STATIC_ROOT

STATIC_ROOT = BASE_DIR / 'static'

It is the absolute path to the directory where python manage.py collectstatic will collect static files for deployment. Example:

/var/www/example.com/static/"

For development, it is not necessary to configure STATIC_ROOT, but extremely important for production. This is the path to be considered by the Nginx, Apache servers to access the website's static files.

STATIC_URL

URL to use when referring to static files located in STATIC_ROOT. Example: "static/" or "http://static.example.com/"

STATIC_URL = '/static/'

Now, suppose I decide to configure the STATIC_URL='/asset/', then I need to change STATIC_ROOT=BASE_DIR / 'asset' and the name of my directory should also be asset.

Reference:

https://docs.djangoproject.com/en/4.0/ref/contrib/staticfiles/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文