Django - 找不到静态文件

发布于 2024-11-07 18:55:07 字数 684 浏览 0 评论 0 原文

我看过有关此问题的几个帖子,但没有找到我的解决方案。

我正在尝试在 Django 1.3 开发环境中提供静态文件。

这是我的设置

...
STATIC_ROOT = '/home/glide/Documents/django/cbox/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
  '/static/',
)
...

我的 urls.py

urlpatterns = patterns('',
...
  url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
    {'document_root', settings.STATIC_ROOT}
  ),
...
);

我的 /home/glide/Documents/django/cbox/static/ 目录就像

css
  main.css
javascript
image

我在尝试访问 http://127.0 时收到 404 错误。 0.1:8000/static/css/main.css

我是否必须分别指定 css、javascript 和图像的模式?

I've seen several posts for this issue but didn't found my solution.

I'm trying to serve static files within my Django 1.3 development environment.

Here are my settings

...
STATIC_ROOT = '/home/glide/Documents/django/cbox/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
  '/static/',
)
...

My urls.py

urlpatterns = patterns('',
...
  url(r'^static/(?P<path>.*)

My /home/glide/Documents/django/cbox/static/ directory is like

css
  main.css
javascript
image

I get a 404 error when trying to access http://127.0.0.1:8000/static/css/main.css.

Do I have to specify patterns for css, javascript and images individually ?

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

My /home/glide/Documents/django/cbox/static/ directory is like


I get a 404 error when trying to access http://127.0.0.1:8000/static/css/main.css.

Do I have to specify patterns for css, javascript and images individually ?

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

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

发布评论

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

评论(16

吃颗糖壮壮胆 2024-11-14 18:55:07

我混淆了STATIC_ROOTSTATICFILES_DIRS

实际上我并没有真正理解STATIC_ROOT的用途。我认为这是我必须放置常用文件的目录。该目录用于生产,这是 收集静态

STATICFILES_DIRS 是我需要的。

由于我处于开发环境中,因此我的解决方案是不使用 STATIC_ROOT (或指定其他路径)并在 STATICFILES_DIRS 中设置我的公共文件目录:

#STATIC_ROOT = (os.path.join(SITE_ROOT, 'static_files/'))
import os
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
STATICFILES_DIRS = (
  os.path.join(SITE_ROOT, 'static/'),
)

也不要不要忘记从 django.conf 导入设置

I confused STATIC_ROOT and STATICFILES_DIRS

Actually I was not really understanding the utility of STATIC_ROOT. I thought that it was the directory on which I have to put my common files. This directory is used for the production, this is the directory on which static files will be put (collected) by collectstatic.

STATICFILES_DIRS is the one that I need.

Since I'm in a development environment, the solution for me is to not use STATIC_ROOT (or to specify another path) and set my common files directory in STATICFILES_DIRS:

#STATIC_ROOT = (os.path.join(SITE_ROOT, 'static_files/'))
import os
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
STATICFILES_DIRS = (
  os.path.join(SITE_ROOT, 'static/'),
)

Also don't forget to from django.conf import settings

挽心 2024-11-14 18:55:07

settings.py 中可能只有两件事会给您带来问题。

1) STATIC_URL = '/static/'

2)

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

并且您的静态文件应位于 static 目录下,该目录与项目的设置文件位于同一目录中。

即使如此,如果您的静态文件未加载,那么原因是,您可能一直将

DEBUG = False

其更改为 True (严格仅用于开发)。在生产中,只需将 STATICFILES_DIRS 更改为静态文件所在的任何路径即可。

There could be only two things in settings.py which causes problems for you.

1) STATIC_URL = '/static/'

2)

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

and your static files should lie under static directory which is in same directory as project's settings file.

Even then if your static files are not loading then reason is , you might have kept

DEBUG = False

change it to True (strictly for development only). In production just change STATICFILES_DIRS to whatever path where static files resides.

箜明 2024-11-14 18:55:07

提供静态文件可以通过多种方式实现;这是我对自己的注释:

  • static/my_app/ 目录添加到 my_app (请参阅下面有关命名空间的注释)
  • 定义一个新的顶级目录并将其添加到 STATICFILES_DIRS 中settings.py (请注意,STATICFILES_DIRS 设置不应包含 STATIC_ROOT 设置

我更喜欢第一种方式,以及接近 在文档中定义,因此为了提供文件 admin-custom.css 来覆盖几个对于管理样式,我有一个像这样的设置:

.
├── my_app/
│   ├── static/
│   │   └── my_app/
│   │       └── admin-custom.css
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── static/
├── templates/
│   └── admin/
│       └── base.html
└── manage.py
# settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'

然后在模板中使用它,如下所示:

# /templates/admin/base.html
{% extends "admin/base.html" %}
{% load static %}

{% block extrahead %}
    <link rel="stylesheet" href="{% static "my_app/admin-custom.css" %}">
{% endblock %}

在开发过程中,如果您使用 django.contrib.staticfiles [ed:默认安装],当 DEBUG 设置为 True 时,这将由 runserver 自动完成 [...]

https://docs.djangoproject.com/en/1.10/howto/static-files/

部署时,我运行 collectstatic 并使用 nginx 提供静态文件。


这些文档为我消除了所有困惑:

STATIC_ROOT

collectstatic 将收集用于部署的静态文件的目录的绝对路径。

...它不是永久存储静态文件的地方。您应该在 staticfiles 的查找器找到的目录中执行此操作,默认情况下,这些目录是“static/”应用程序子目录以及您包含在 STATICFILES_DIRS 中的任何目录。

https://docs.djangoproject.com/en/1.10/ref/settings/ #静态根


静态文件命名空间

现在我们也许可以将静态文件直接放在 my_app/static/ 中(而不是创建另一个 my_app 子目录),但这实际上是一个坏主意。 Django 将使用它找到的名称匹配的第一个静态文件,如果您在不同的应用程序中有一个具有相同名称的静态文件,Django 将无法区分它们。我们需要能够将 Django 指向正确的位置,而确保这一点的最简单方法是通过命名它们。也就是说,将这些静态文件放入以应用程序本身命名的另一个目录中。

https://docs.djangoproject.com/en/1.10/howto/static-files/


STATICFILES_DIRS

您的项目可能还会有不与特定应用程序绑定的静态资源。除了在应用程序中使用 static/ 目录之外,您还可以在设置文件中定义目录列表 (STATICFILES_DIRS),Django 还将在其中查找静态文件。

https://docs.djangoproject.com/en/1.10/howto/static-files/

Serving static files can be achieved in several ways; here are my notes to self:

  • add a static/my_app/ directory to my_app (see the note about namespacing below)
  • define a new top level directory and add that to STATICFILES_DIRS in settings.py (note that The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting)

I prefer the first way, and a setup that's close to the way defined in the documentation, so in order to serve the file admin-custom.css to override a couple of admin styles, I have a setup like so:

.
├── my_app/
│   ├── static/
│   │   └── my_app/
│   │       └── admin-custom.css
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── static/
├── templates/
│   └── admin/
│       └── base.html
└── manage.py
# settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'

This is then used in the template like so:

# /templates/admin/base.html
{% extends "admin/base.html" %}
{% load static %}

{% block extrahead %}
    <link rel="stylesheet" href="{% static "my_app/admin-custom.css" %}">
{% endblock %}

During development, if you use django.contrib.staticfiles [ed: installed by default], this will be done automatically by runserver when DEBUG is set to True [...]

https://docs.djangoproject.com/en/1.10/howto/static-files/

When deploying, I run collectstatic and serve static files with nginx.


The docs which cleared up all the confusion for me:

STATIC_ROOT

The absolute path to the directory where collectstatic will collect static files for deployment.

...it is not a place to store your static files permanently. You should do that in directories that will be found by staticfiles’s finders, which by default, are 'static/' app sub-directories and any directories you include in STATICFILES_DIRS).

https://docs.djangoproject.com/en/1.10/ref/settings/#static-root


Static file namespacing

Now we might be able to get away with putting our static files directly in my_app/static/ (rather than creating another my_app subdirectory), but it would actually be a bad idea. Django will use the first static file it finds whose name matches, and if you had a static file with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the easiest way to ensure this is by namespacing them. That is, by putting those static files inside another directory named for the application itself.

https://docs.djangoproject.com/en/1.10/howto/static-files/


STATICFILES_DIRS

Your project will probably also have static assets that aren’t tied to a particular app. In addition to using a static/ directory inside your apps, you can define a list of directories (STATICFILES_DIRS) in your settings file where Django will also look for static files.

https://docs.djangoproject.com/en/1.10/howto/static-files/

弃爱 2024-11-14 18:55:07

如果您的静态 URL 正确但仍然:

未找到:/static/css/main.css

也许是您的 WSGI 问题。

➡配置 WSGI 同时服务于开发环境和生产环境

==========================project/project/wsgi.py==========================

import os
from django.conf import settings
from django.contrib.staticfiles.handlers import StaticFilesHandler
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
if settings.DEBUG:
    application = StaticFilesHandler(get_wsgi_application())
else:
    application = get_wsgi_application()

If your static URL is correct but still:

Not found: /static/css/main.css

Perhaps your WSGI problem.

➡ Config WSGI serves both development env and production env

==========================project/project/wsgi.py==========================

import os
from django.conf import settings
from django.contrib.staticfiles.handlers import StaticFilesHandler
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
if settings.DEBUG:
    application = StaticFilesHandler(get_wsgi_application())
else:
    application = get_wsgi_application()
赏烟花じ飞满天 2024-11-14 18:55:07
  1. 您可以删除 STATIC_ROOT
  2. ,或者您可以在不同的目录中创建另一个 static 文件夹。假设目录是:project\static
    现在更新:
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'project/static/')
    ]
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')

无论您做什么,要点是 STATICFILES_DIRSSTATIC_ROOT 不应包含相同的目录。

我知道已经过去很长时间了,但希望新朋友能从中得到帮助

  1. You can remove the STATIC_ROOT line
  2. Or you can create another static folder in different directory. For suppose the directory is: project\static
    Now update:
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'project/static/')
    ]
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')

Whatever you do the main point is STATICFILES_DIRS and STATIC_ROOT should not contain same directory.

I know it's been a long time but hope the new buddies can get help from it

调妓 2024-11-14 18:55:07

STATICFILES_DIRS 用于开发STATIC_ROOT 用于生产

STATICFILES_DIRS STATIC_ROOT 不应具有相同的文件夹名称,

如果您需要在开发和生产中使用完全相同的静态文件夹,请尝试此方法,

将其包含在 settings.py

import socket

HOSTNAME = socket.gethostname()

# if hostname same as production url name use STATIC_ROOT 
if HOSTNAME == 'www.example.com':
    STATIC_ROOT = os.path.join(BASE_DIR, "static/")

else:
    STATICFILES_DIRS = [
            os.path.join(BASE_DIR, 'static/'),
        ]

STATICFILES_DIRS is used in development and STATIC_ROOT in production,

STATICFILES_DIRS and STATIC_ROOT should not have same folder name,

If you need to use the exact same static folder in development and production, try this method

include this in settings.py

import socket

HOSTNAME = socket.gethostname()

# if hostname same as production url name use STATIC_ROOT 
if HOSTNAME == 'www.example.com':
    STATIC_ROOT = os.path.join(BASE_DIR, "static/")

else:
    STATICFILES_DIRS = [
            os.path.join(BASE_DIR, 'static/'),
        ]
错々过的事 2024-11-14 18:55:07

另一个错误可能是您的应用没有列在 INSTALLED_APPS 列表中,例如:

INSTALLED_APPS = [
    # ...
    'your_app',
]

如果没有将其列在其中,您可能会面临诸如未检测到静态文件(基本上是涉及您的应用的所有文件)之类的问题。即使它可以按照正确答案中的建议是正确的,方法是:

STATICFILES_DIRS = (adding/path/of/your/app)

可能是错误之一,如果出现此错误,应进行审查。

Another error can be not having your app listed in the INSTALLED_APPS listing like:

INSTALLED_APPS = [
    # ...
    'your_app',
]

Without having it in, you can face problems like not detecting your static files, basically all the files involving your app. Even though it can be correct as suggested in the correct answer by using:

STATICFILES_DIRS = (adding/path/of/your/app)

Can be one of the errors and should be reviewed if getting this error.

愛放△進行李 2024-11-14 18:55:07

在你的cmd中输入命令
python manage.py findstatic --verbosity 2 static
它将给出 Django 在其中查找静态文件的目录。如果您创建了虚拟环境,那么此 virtual_environment_name 文件夹中将会有一个 static 文件夹。
VIRTUAL_ENVIRONMENT_NAME\Lib\site-packages\django\contrib\admin\static
在运行上面的“findstatic”命令时,如果 Django 显示此路径,则只需将所有静态文件粘贴到此静态目录中。
在您的 html 文件中,使用 JINJA 语法作为 href 并检查其他内联 css。如果在给出 JINJA 语法后仍然存在图像 src 或 url,则在其前面加上 '/static'。
这对我有用。

In your cmd type command
python manage.py findstatic --verbosity 2 static
It will give the directory in which Django is looking for static files.If you have created a virtual environment then there will be a static folder inside this virtual_environment_name folder.
VIRTUAL_ENVIRONMENT_NAME\Lib\site-packages\django\contrib\admin\static.
On running the above 'findstatic' command if Django shows you this path then just paste all your static files in this static directory.
In your html file use JINJA syntax for href and check for other inline css. If still there is an image src or url after giving JINJA syntax then prepend it with '/static'.
This worked for me.

白昼 2024-11-14 18:55:07

我通过在 INSTALLED_APPS 中添加我的项目名称来解决此问题。在此处输入图像描述

I solve this problem by adding my project name in INSTALLED_APPS.enter image description here

不气馁 2024-11-14 18:55:07
TEMPLATE_DIR=os.path.join(BASE_DIR,'templates')
STATIC_DIR=os.path.join(BASE_DIR,'static')

STATICFILES_DIRS=[STATIC_DIR]
TEMPLATE_DIR=os.path.join(BASE_DIR,'templates')
STATIC_DIR=os.path.join(BASE_DIR,'static')

STATICFILES_DIRS=[STATIC_DIR]
小情绪 2024-11-14 18:55:07

始终记住 Django 文件末尾的两件事 settings.py

用于开发

STATIC_URL = '/static/'

用于生产

STATIC_ROOT = '/static/'

由于您在开发环境中工作,请注释掉 settings.py 中的其他两个路径> 文件

#STATIC_ROOT = '/home/glide/Documents/django/cbox/static/'
STATIC_URL = '/static/'
#STATICFILES_DIRS = (
#  '/static/',
#)

并对 urls.py 进行如下更改

urlpatterns = patterns('',
...
  url(r'^static/(?P<path>.*)

希望这可以解决问题

, 'django.views.static.serve', {'document_root', settings.STATIC_URL} ), ... );

希望这可以解决问题

Always remember two things in Django at the end of file settings.py

For development

STATIC_URL = '/static/'

For production

STATIC_ROOT = '/static/'

Since you are working in a development environment, comment out the other two paths from settings.py file

#STATIC_ROOT = '/home/glide/Documents/django/cbox/static/'
STATIC_URL = '/static/'
#STATICFILES_DIRS = (
#  '/static/',
#)

And for the urls.py make changes as follows

urlpatterns = patterns('',
...
  url(r'^static/(?P<path>.*)

Hope this may solve the problems

, 'django.views.static.serve', {'document_root', settings.STATIC_URL} ), ... );

Hope this may solve the problems

幸福还没到 2024-11-14 18:55:07

Django 没有用于提供静态文件的内置解决方案,至少在 DEBUG 必须为 False 的生产中是这样。

我们必须使用第三方解决方案来完成此任务。

要在虚拟环境中安装 WhiteNoise,请键入以下命令:

pip install whitenoise

然后修改设置

要让 Django 知道您想要运行 WhitNoise,您必须在 settings.py 文件的 MIDDLEWARE 列表中指定它:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
].

Django does not have a built-in solution for serving static files, at least not in production when DEBUG has to be False.

We have to use a third-party solution to accomplish this.

To install WhiteNoise in your virtual environment, type the command below:

pip install whitenoise

then Modify Settings

To make Django aware of you wanting to run WhitNoise, you have to specify it in the MIDDLEWARE list in settings.py file:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
].
落花随流水 2024-11-14 18:55:07

如果您在开发环境中,则需要定义 STATIC_URLSTATICFILES_DIR;如果您在生产环境中,则需要定义 STATIC_URL >STATIC_ROOT

对于 Windows:

STATIC_URL = 'static/'

STATICFILES_DIRS = (
   
    os.path.join(BASE_DIR, 'static'),
)

以及 Linux 环境

SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
     STATICFILES_DIRS = (os.path.join(SITE_ROOT, 'static'),)

If you are on development environment you will need to define STATIC_URL and STATICFILES_DIR and if you are on production environment you need to define STATIC_URL and STATIC_ROOT

For windows:

STATIC_URL = 'static/'

STATICFILES_DIRS = (
   
    os.path.join(BASE_DIR, 'static'),
)

And for linux environment

SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
     STATICFILES_DIRS = (os.path.join(SITE_ROOT, 'static'),)
薄荷→糖丶微凉 2024-11-14 18:55:07

我发现我将本地设置中的 DEBUG 设置移动为被默认 False 值覆盖。如果您使用 DEBUGrunserver 进行开发,本质上要确保 DEBUG 设置实际上为 false。

I found that I moved my DEBUG setting in my local settings to be overwritten by a default False value. Essentially look to make sure the DEBUG setting is actually false if you are developing with DEBUG and runserver.

壹場煙雨 2024-11-14 18:55:07

如果您添加了 django-storages 模块(例如,支持在 django 应用程序中将文件上传到 S3),并且像我一样您没有正确阅读 此模块的文档,只需从 settings.py 中删除此行

STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

否则,它将导致您的静态资产不在本地计算机上查看,而是在 S3 存储桶中远程查看,包括管理面板 CSS,从而有效地破坏管理面板 CSS。

If you've have added the django-storages module (to support uploading files to S3 in your django app for instance), and if like me you did not read correctly the documentation of this module, just remove this line from your settings.py:

STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

Otherwise it will cause your static assets to be looked NOT on your local machine but remotely in the S3 bucket, including admin panel CSS, and thus effectively breaking admin panel CSS.

夏见 2024-11-14 18:55:07

您只需要用于开发:

STATIC_URL = '/staticfiles/'
STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, 'staticfiles'),
)

用于生产(使用 /manage.pycollectstatic 时):

STATIC_ROOT  =   os.path.join(PROJECT_ROOT, 'static')

在 Debug = False 之后,您的静态文件将不会加载。您可以通过输入 127.0.0.1:8000/staticfiles/css/main.css (例如)来检查它。
因此,您需要更改为 Debug = True,然后通过 Ctrl+F5 重新加载页面。

You need only for Development:

STATIC_URL = '/staticfiles/'
STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, 'staticfiles'),
)

For Production (when using /manage.py collectstatic):

STATIC_ROOT  =   os.path.join(PROJECT_ROOT, 'static')

After Debug = False your static files will not loading. You can check it via entering to 127.0.0.1:8000/staticfiles/css/main.css (for example).
So, you need change to Debug = True and then reload the page via Ctrl+F5.

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