[英]Django -- Can't get static CSS files to load
I'm running Django's development server ( runserver
) on my local machine (Mac OS X) and cannot get the CSS files to load.我在本地计算机 (Mac OS X) 上运行 Django 的开发服务器 (
runserver
),但无法加载 CSS 文件。
Here are the relevant entries in settings.py:以下是 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:在我的 views.py 中,我请求上下文:
return render_to_response("cal/main.html",dict(entries=entries),context_instance=RequestContext(request))
And in my template the {{ STATIC_URL }}
renders correctly:在我的模板中,
{{ STATIC_URL }}
正确呈现:
<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.我还运行了
collectstatic
以确保收集了所有文件。
I also have the following lines in my urls.py:我的 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.我是 Django 的新手,所以可能遗漏了一些简单的东西——希望得到任何帮助。
Read this carefully: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/仔细阅读: https : //docs.djangoproject.com/en/dev/ref/contrib/staticfiles/
Is django.contrib.staticfiles
in your INSTALLED_APPS
in settings.py
?在
settings.py
的INSTALLED_APPS
中是django.contrib.staticfiles
吗?
Is DEBUG=False
?是
DEBUG=False
吗? If so, you need to call runserver
with the --insecure
parameter:如果是这样,您需要使用
--insecure
参数调用runserver
:
python manage.py runserver --insecure
collectstatic
has no bearing on serving files via the development server. collectstatic
与通过开发服务器提供文件无关。 It is for collecting the static files in one location STATIC_ROOT
for your web server to find them.它用于在一个位置
STATIC_ROOT
收集静态文件,以便您的 Web 服务器找到它们。 In fact, running collectstatic
with your STATIC_ROOT
set to a path in STATICFILES_DIRS
is a bad idea.事实上,运行
collectstatic
与STATIC_ROOT
设置为路径STATICFILES_DIRS
是一个坏主意。 You should double-check to make sure your CSS files even exist now.您应该仔细检查以确保您的 CSS 文件现在甚至存在。
For recent releases of Django, You have to configure static files in settings.py
as,对于最近发布的 Django,您必须在
settings.py
中将静态文件settings.py
为,
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' %}">
Another simple thing to try is to stop, and then restart the server eg另一个简单的尝试是停止,然后重新启动服务器,例如
$ python manage.py runserver
I looked into the other answers, but restarting the server worked for me.我查看了其他答案,但重新启动服务器对我有用。
Add the following code to your settings.py
:将以下代码添加到
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"/>
Are these missing from your settings.py
?您的
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
:另外,这就是我在
urls.py
:
urlpatterns += patterns('', (
r'^static/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': 'static'}
))
DEBUG = True
在我的本地设置中为我做了。
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并从
settings.py
删除了STATIC_ROOT
,它对我STATIC_ROOT
These steps work for me, just see Load Static Files (CSS, JS, & Images) in Django这些步骤对我有用,请参阅在 Django 中加载静态文件(CSS、JS 和图像)
I use Django 1.10.我使用 Django 1.10。
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/
;settings.py
的同一级别上创建一个static
文件夹,我的settings.py
的路径是~/djcode/mysite/mysite/settings.py
,所以这个目录是~/djcode/mysite/mysite/static/
;static_dirs
and static_root
in static
, that's ~/djcode/mysite/mysite/static/static_dirs/
and ~/djcode/mysite/mysite/static/static_root/
;static
创建两个文件夹static_dirs
和static_root
,即~/djcode/mysite/mysite/static/static_dirs/
和~/djcode/mysite/mysite/static/static_root/
; write settings.py
like this:像这样写
settings.py
:
# 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'), )
do this command $ python manage.py collectstatic
in shell;在 shell 中执行此命令
$ python manage.py collectstatic
;
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
;在
static_dirs
创建一个文件夹css
并放入您自己的.css
文件中,您的 css 文件的路径是~/djcode/mysite/mysite/static/static_dirs/css/my_style.css
;
change <link>
tag in .html
file: <link rel="stylesheet" type="text/css" href="{% static 'css/my_style.css' %}">
,更改
.html
文件中的<link>
标签: <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
最后这个链接的路径是
http://192.168.1.100:8023/static/css/my_style.css
Bingo!答对了!
You had same path in STATICFILES_DIRS AND STATIC_ROOT, I ran into the same issue and below was the exception -你在 STATICFILES_DIRS 和 STATIC_ROOT 中有相同的路径,我遇到了同样的问题,下面是例外 -
ImproperlyConfigured: The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting ImproperlyConfigured:STATICFILES_DIRS 设置不应包含 STATIC_ROOT 设置
For local you don't need STATICFILES_DIRS, as anyway you don't need to run collectstatic.对于本地,您不需要 STATICFILES_DIRS,因为无论如何您都不需要运行 collectstatic。 Once you comment it, it should work fine.
一旦你评论它,它应该可以正常工作。
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... ???这加载了需要的东西,但出于某种原因,我经历过有时没有这个就可以工作......???
I tried this model and it worked.我试过这个模型,它奏效了。
Changes in settings as per the django project created with shell根据使用 shell 创建的 django 项目更改设置
"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: xxx的结构是:
> .
> |-- 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 - 在 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 - 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'^$', DirectTemplateView.as_view(template_name="home.html")), )
- home.html - 主页.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>
I had to use我不得不使用
STATICFILES_DIRS = ( '/home/USERNAME/webapps/django/PROJECT/static/', )
That helped me.那帮助了我。
See if your main application (where the static directory is located) is included in your INSTALLED_APPS.查看您的主应用程序(静态目录所在的位置)是否包含在您的 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.
默认是在 STATICFILES_DIRS 中定义的所有位置和 INSTALLED_APPS 设置指定的应用程序的“静态”目录中查找。
Add this "django.core.context_processors.static",
context processor in your settings.py在 settings.py 中添加这个
"django.core.context_processors.static",
上下文处理器
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.static",
) )
You can just set STATIC_ROOT depending on whether you are running on your localhost or on your server.您可以根据您是在本地主机上还是在服务器上运行来设置 STATIC_ROOT。 To identify that, refer to this post .
要确定这一点,请参阅这篇文章。
And you can rewrite you STATIC_ROOT configuration as:您可以将 STATIC_ROOT 配置重写为:
import sys
if 'runserver' in sys.argv:
STATIC_ROOT = ''
else:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
If you set DEBUG=FALSE you need to do follow steps如果您设置 DEBUG=FALSE,则需要执行以下步骤
In your urls.py file: add this line在您的 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}),
I have the same issue (ununtu 16.04 server).我有同样的问题(ununtu 16.04 服务器)。
This helped me这帮助了我
python manage.py collectstatic --noinput
python manage.py collectstatic --noinput
add following in settings.py在 settings.py 中添加以下内容
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Two most Basis points to be noted for running Static files in Django Application are - Declare static file path in your settings.py
file在 Django 应用程序中运行静态文件最需要注意的两个基本点是 - 在
settings.py
文件中声明静态文件路径
STATIC_URL = '/static/'
Another important parameter is the web page in which you are using static keyword, you need to load the static files.另一个重要参数是您使用 static 关键字的网页,您需要加载静态文件。
{% load static %}
Go to your HTML page load static by转到您的 HTML 页面加载静态
{% 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你做对了
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我有同样的问题检查你的 settings.py 并确保 STATIC_URL = '/static/' 在我的情况下首先/在开始时丢失,这导致所有 static 文件无法工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.