Django——无法加载静态 CSS 文件

发布于 2024-12-06 16:51:16 字数 1238 浏览 3 评论 0原文

我正在本地计算机 (Mac OS X) 上运行 Django 的开发服务器 (runserver),但无法加载 CSS 文件。

以下是settings.py中的相关条目:

STATIC_ROOT = '/Users/username/Projects/mysite/static/'

STATIC_URL = '/static/'

STATICFILES_DIRS = (
'/Users/thaymore/Projects/mysite/cal/static',
)

STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

INSTALLED_APPS = (
# other apps ...
'django.contrib.staticfiles',
)

在我的views.py中,我请求上下文:

return render_to_response("cal/main.html",dict(entries=entries),context_instance=RequestContext(request))

在我的模板中, {{ STATIC_URL }} 正确呈现:

<link type="text/css" href="{{ STATIC_URL }}css/main.css" />

变成:

<link type="text/css" href="/static/css/main.css"/>

文件所在的位置实际上位于。我还运行了 collectstatic 以确保收集所有文件。

我的 urls.py 中也有以下几行:

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns += staticfiles_urlpatterns()

我是 Django 新手,所以可能缺少一些简单的东西 - 希望得到任何帮助。

I'm running Django's development server (runserver) on my local machine (Mac OS X) and cannot get the CSS files to load.

Here are the relevant entries in settings.py:

STATIC_ROOT = '/Users/username/Projects/mysite/static/'

STATIC_URL = '/static/'

STATICFILES_DIRS = (
'/Users/thaymore/Projects/mysite/cal/static',
)

STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

INSTALLED_APPS = (
# other apps ...
'django.contrib.staticfiles',
)

In my views.py I'm requesting the context:

return render_to_response("cal/main.html",dict(entries=entries),context_instance=RequestContext(request))

And in my template the {{ STATIC_URL }} renders correctly:

<link type="text/css" href="{{ STATIC_URL }}css/main.css" />

Turns into:

<link type="text/css" href="/static/css/main.css"/>

Which is where the file is actually located. I also ran collectstatic to make sure all the files were collected.

I also have the following lines in my urls.py:

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns += staticfiles_urlpatterns()

I'm new to Django so am probably missing something simple -- would appreciate any help.

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

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

发布评论

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

评论(21

你在我安 2024-12-13 16:51:16

仔细阅读以下内容:
https://docs.djangoproject.com/en/dev/ref/contrib/ staticfiles/

django.contrib.staticfiles 是否位于 settings.py 中的 INSTALLED_APPS 中?

DEBUG=False吗?如果是这样,您需要使用 --insecure 参数调用 runserver

python manage.py runserver --insecure

collectstatic 与通过开发服务器提供文件无关。它用于将静态文件收集到一个位置STATIC_ROOT,以便您的网络服务器找到它们。事实上,在将 STATIC_ROOT 设置为 STATICFILES_DIRS 中的路径的情况下运行 collectstatic 是一个坏主意。您应该仔细检查以确保您的 CSS 文件现在存在。

Read this carefully:
https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/

Is django.contrib.staticfiles in your INSTALLED_APPS in settings.py?

Is DEBUG=False? If so, you need to call runserver with the --insecure parameter:

python manage.py runserver --insecure

collectstatic has no bearing on serving files via the development server. It is for collecting the static files in one location STATIC_ROOT for your web server to find them. In fact, running collectstatic with your STATIC_ROOT set to a path in STATICFILES_DIRS is a bad idea. You should double-check to make sure your CSS files even exist now.

音栖息无 2024-12-13 16:51:16

对于最新版本的 Django,您必须在 settings.py 中配置静态文件,

STATIC_URL = '/static/' # the path in url

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

并将其与静态模板标签一起使用,

{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">

For recent releases of Django, You have to configure static files in settings.py as,

STATIC_URL = '/static/' # the path in url

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

and use it with static template tag,

{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
∞梦里开花 2024-12-13 16:51:16

另一个简单的尝试是停止,然后重新启动服务器,例如

$ python manage.py runserver

我查看了其他答案,但重新启动服务器对我有用。

Another simple thing to try is to stop, and then restart the server e.g.

$ python manage.py runserver

I looked into the other answers, but restarting the server worked for me.

时常饿 2024-12-13 16:51:16

您的 settings.py 中是否缺少这些内容?我正在粘贴我的项目设置之一:

TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages")

另外,这是我的 urls.py 中的内容:

urlpatterns += patterns('', (
        r'^static/(?P<path>.*)
,
        'django.views.static.serve',
        {'document_root': 'static'}
))

Are these missing from your settings.py? I am pasting one of my project's settings:

TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages")

Also, this is what I have in my urls.py:

urlpatterns += patterns('', (
        r'^static/(?P<path>.*)
,
        'django.views.static.serve',
        {'document_root': 'static'}
))
§对你不离不弃 2024-12-13 16:51:16

settings.py添加

PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__))
STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, "static"), )

和删除 STATIC_ROOT,它对我有用

added

PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__))
STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, "static"), )

and removed STATIC_ROOT from settings.py, It worked for me

单身狗的梦 2024-12-13 16:51:16

将以下代码添加到您的 settings.py 中:

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

之后,在项目的根目录中创建 static 文件夹。

要在模板上加载静态文件,请使用:

{% load static %}
  <img src="{% static "images/index.jpeg" %}" alt="My image"/>

Add the following code to your settings.py:

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

After that, create the static folder at the root directory of your project.

To load the static files on templates use:

{% load static %}
  <img src="{% static "images/index.jpeg" %}" alt="My image"/>
别再吹冷风 2024-12-13 16:51:16

我的本地设置中的 DEBUG = True 为我做到了。

DEBUG = True in my local settings did it for me.

沦落红尘 2024-12-13 16:51:16

这些步骤对我有用,只需参阅 在 Django 中加载静态文件(CSS、JS 和图像)< /a>

我使用 Django 1.10。

  1. settings.py同级创建一个文件夹static,我的settings.py的路径是~/djcode/mysite /mysite/settings.py,所以这个目录是~/djcode/mysite/mysite/static/
  2. static中创建两个文件夹static_dirsstatic_root,即~/djcode/mysite/mysite/static/static_dirs/~/djcode/mysite/mysite/static/static_root/
  3. 像这样编写settings.py

    # 静态文件(CSS、JavaScript、图像)
    
    # https://docs.djangoproject.com/en/1.10/howto/static-files/
    
    STATIC_URL = '/静态/'
    
    STATIC_ROOT = os.path.join(BASE_DIR, 'mysite', 'static', 'static_root')
    
    静态文件目录 = (
        os.path.join(BASE_DIR, 'mysite', 'static', 'static_dirs'),
    )
    
  4. 在shell中执行此命令$ python manage.pycollectstatic;

  5. static_dirs中创建一个文件夹css并放入您自己的.css文件中,您的css文件路径为~/ djcode/mysite/mysite/static/static_dirs/css/my_style.css;

  6. 更改 .html 文件中的 标记:,

最后这个链接的路径是 http://192.168.1.100:8023/static/ css/my_style.css

宾果!

These steps work for me, just see Load Static Files (CSS, JS, & Images) in Django

I use Django 1.10.

  1. create a folder static on the same level of settings.py, my settings.py's path is ~/djcode/mysite/mysite/settings.py, so this dir is ~/djcode/mysite/mysite/static/;
  2. create two folders static_dirs and static_root in static, that's ~/djcode/mysite/mysite/static/static_dirs/ and ~/djcode/mysite/mysite/static/static_root/;
  3. write settings.py like this:

    # Static files (CSS, JavaScript, Images)
    
    # https://docs.djangoproject.com/en/1.10/howto/static-files/
    
    STATIC_URL = '/static/'
    
    STATIC_ROOT = os.path.join(BASE_DIR, 'mysite', 'static', 'static_root')
    
    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'mysite', 'static', 'static_dirs'),
    )
    
  4. do this command $ python manage.py collectstatic in shell;

  5. create a folder css in static_dirs and put into your own .css file, your css file' path is ~/djcode/mysite/mysite/static/static_dirs/css/my_style.css;

  6. change <link> tag in .html file: <link rel="stylesheet" type="text/css" href="{% static 'css/my_style.css' %}">,

Finally this link's path is http://192.168.1.100:8023/static/css/my_style.css

Bingo!

云醉月微眠 2024-12-13 16:51:16

您在 STATICFILES_DIRS 和 STATIC_ROOT 中有相同的路径,我遇到了同样的问题,下面是例外 -

ImproperlyConfigured: The STATICFILES_DIRS 设置不应包含 STATIC_ROOT 设置

对于本地,您不需要 STATICFILES_DIRS,因为无论如何您不需要运行收集静态。一旦你评论它,它应该可以正常工作。

You had same path in STATICFILES_DIRS AND STATIC_ROOT, I ran into the same issue and below was the exception -

ImproperlyConfigured: The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting

For local you don't need STATICFILES_DIRS, as anyway you don't need to run collectstatic. Once you comment it, it should work fine.

渡你暖光 2024-12-13 16:51:16

您是否在模板中添加了:

{% load staticfiles %}

这会加载所需的内容,但由于某种原因,我经历过有时没有这个就可以工作...???

Have you added into your templates:

{% load staticfiles %}

This loads what's needed, but for some reason I have experienced that sometimes work without this... ???

从此见与不见 2024-12-13 16:51:16

我必须使用

STATICFILES_DIRS = ( '/home/USERNAME/webapps/django/PROJECT/static/', )

这对我有帮助。

I had to use

STATICFILES_DIRS = ( '/home/USERNAME/webapps/django/PROJECT/static/', )

That helped me.

∝单色的世界 2024-12-13 16:51:16

查看您的主应用程序(静态目录所在的位置)是否包含在您的 INSTALLED_APPS 中。

使用启用的查找器搜索文件。默认情况下是在 STATICFILES_DIRS 中定义的所有位置以及 INSTALLED_APPS 设置指定的应用程序的“静态”目录中查找。

See if your main application (where the static directory is located) is included in your INSTALLED_APPS.

Files are searched by using the enabled finders. The default is to look in all locations defined in STATICFILES_DIRS and in the 'static' directory of apps specified by the INSTALLED_APPS setting.

疯了 2024-12-13 16:51:16

我尝试了这个模型并且成功了。

根据使用 shell 创建的 django 项目更改设置,

"django-admin.py startproject xxx"# here xxx is my app name

修改文件夹如下结构加载我们的静态文件以在服务器上运行

xxx 的结构是:

>     .
>     |-- manage.py
>     |-- templates
>     |   `-- home.html
>     `-- test_project
>         |-- __init__.py
>         |-- settings.py
>         |-- static
>         |   |-- images
>         |   |   `-- 01.jpg
>         |   |-- style.css
>         |-- urls.py
>         `-- wsgi.py

- Settings.py 中的修改

import os
INSTALLED_APPS = (    'xxx',# my app is to be load into it)

STATIC_ROOT = ''
STATIC_URL = '/static/'
PROJECT_DIR = os.path.dirname(__file__)
TEMPLATE_DIRS = (      os.path.join(PROJECT_DIR, '../templates'),)#include this 

- urls.py 中的修改

from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView

class DirectTemplateView(TemplateView):
    extra_context = None
    def get_context_data(self, **kwargs):
        context = super(self.__class__, self).get_context_data(**kwargs)
        if self.extra_context is not None:
            for key, value in self.extra_context.items():
                if callable(value):
                    context[key] = value()
                else:
                    context[key] = value
        return context

urlpatterns = patterns('', 
    url(r'^

- home.html

<html>
    <head>
        <link href="{{STATIC_URL}}style.css" rel="stylesheet" type="text/css">
    </head>
    <body>
        <h1>This is home for some_app</h1>
      <img src="{{STATIC_URL}}/images/01.jpg" width=150px;height=150px; alt="Smiley ">
    </body>
</html>
, DirectTemplateView.as_view(template_name="home.html")), )

- home.html

I tried this model and it worked.

Changes in settings as per the django project created with shell

"django-admin.py startproject xxx"# here xxx is my app name

modify the folder as below structure loading our static files to run on server

Structure of xxx is:

>     .
>     |-- manage.py
>     |-- templates
>     |   `-- home.html
>     `-- test_project
>         |-- __init__.py
>         |-- settings.py
>         |-- static
>         |   |-- images
>         |   |   `-- 01.jpg
>         |   |-- style.css
>         |-- urls.py
>         `-- wsgi.py

- modifications in Settings.py

import os
INSTALLED_APPS = (    'xxx',# my app is to be load into it)

STATIC_ROOT = ''
STATIC_URL = '/static/'
PROJECT_DIR = os.path.dirname(__file__)
TEMPLATE_DIRS = (      os.path.join(PROJECT_DIR, '../templates'),)#include this 

- modifications in urls.py

from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView

class DirectTemplateView(TemplateView):
    extra_context = None
    def get_context_data(self, **kwargs):
        context = super(self.__class__, self).get_context_data(**kwargs)
        if self.extra_context is not None:
            for key, value in self.extra_context.items():
                if callable(value):
                    context[key] = value()
                else:
                    context[key] = value
        return context

urlpatterns = patterns('', 
    url(r'^

- home.html

<html>
    <head>
        <link href="{{STATIC_URL}}style.css" rel="stylesheet" type="text/css">
    </head>
    <body>
        <h1>This is home for some_app</h1>
      <img src="{{STATIC_URL}}/images/01.jpg" width=150px;height=150px; alt="Smiley ">
    </body>
</html>
, DirectTemplateView.as_view(template_name="home.html")), )

- home.html

悸初 2024-12-13 16:51:16

在您的 settings.py 中添加此 "django.core.context_processors.static", 上下文处理器

TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.static",

Add this "django.core.context_processors.static", context processor in your settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.static",

)

变身佩奇 2024-12-13 16:51:16

您可以根据您是在本地主机上运行还是在服务器上运行来设置 STATIC_ROOT 。要确定这一点,请参阅此

您可以将 STATIC_ROOT 配置重写为:

import sys

if 'runserver' in sys.argv:
    STATIC_ROOT = ''
else:
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'

You can just set STATIC_ROOT depending on whether you are running on your localhost or on your server. To identify that, refer to this post.

And you can rewrite you STATIC_ROOT configuration as:

import sys

if 'runserver' in sys.argv:
    STATIC_ROOT = ''
else:
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
﹉夏雨初晴づ 2024-12-13 16:51:16

如果设置 DEBUG=FALSE
您需要

在 urls.py 文件中执行以下步骤:
添加这一行

from django.views.static import serve

url(r'^media/(?P<path>.*)
, serve,{'document_root': settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)
, serve,{'document_root': settings.STATIC_ROOT}),

If you set DEBUG=FALSE
you need to do follow steps

In your urls.py file:
add this line

from django.views.static import serve

url(r'^media/(?P<path>.*)
, serve,{'document_root': settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)
, serve,{'document_root': settings.STATIC_ROOT}),

半衾梦 2024-12-13 16:51:16

我有同样的问题(ununtu 16.04 服务器)。

这对我有帮助

python Manage.pycollectstatic--noinput

I have the same issue (ununtu 16.04 server).

This helped me

python manage.py collectstatic --noinput

筑梦 2024-12-13 16:51:16

在settings.py中添加以下内容

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')  
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

add following in settings.py

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')  
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
无力看清 2024-12-13 16:51:16

在 Django 应用程序中运行静态文件需要注意的两个最基础的点是 - 在 settings.py 文件中声明静态文件路径

STATIC_URL = '/static/'

另一个重要的参数是您使用 static 关键字的网页,您需要加载静态文件。

{% load static %}

Two most Basis points to be noted for running Static files in Django Application are - Declare static file path in your settings.py file

STATIC_URL = '/static/'

Another important parameter is the web page in which you are using static keyword, you need to load the static files.

{% load static %}
别靠近我心 2024-12-13 16:51:16

转到您的 HTML 页面加载静态

{% load static %}

现在我犯的唯一错误是这个

我的代码:

<img src="**{% static** "images/index.jpeg" %}" alt="My image">

更新:

<img src=**"{% static 'images/index.jpeg' %}' alt="My image"**>

你说得对

Go to your HTML page load static by

{% load static %}

Now only mistake I've made was this

My code:

<img src="**{% static** "images/index.jpeg" %}" alt="My image">

Updated:

<img src=**"{% static 'images/index.jpeg' %}' alt="My image"**>

You get it right

别挽留 2024-12-13 16:51:16

我遇到了同样的问题,请检查您的 settings.py 并确保 STATIC_URL = '/static/'
就我而言,第一个/开头丢失,这导致所有静态文件无法工作

I had same issue check your settings.py and make sure STATIC_URL = '/static/'
in my case first / at the beginning was missing and that was causing all static files not to work

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