Django中静态文件无法显示

4
<!DOCTYPE html>
{% load staticfiles %}
<html>
........
<img src="{% static 'images/parralax/spaces.jpg' %}"  width = 250px  />
<body>

以上代码无法显示我设置的背景图片。我不确定该如何解决这个问题。

以下是我的设置文件。我认为问题出在链接到CSS上没有生效。 提前致谢!

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
STATIC_DIR = os.path.join(BASE_DIR, 'static')
MEDIA_DIR = os.path.join(BASE_DIR,'media')


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR,],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [.....
            ],
        },
    },
]

STATICFILES_DIRS = [STATIC_DIR,  ]
STATIC_URL = '/static/'
MEDIA_ROOT = MEDIA_DIR #where to look for files
MEDIA_URL = '/media/' #where to serve files from on url
WSGI_APPLICATION = 'Space.wsgi.application'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')

.....


.....
urls.py
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^Spaces/', include('Spaces.urls')),
    #Django Admin
    path('admin/', admin.site.urls),
    #User Management
    url(r'^accounts/', include('allauth.urls')),
    path(r'^users/', include('users.urls')),
    path(r'^users/', include('django.contrib.auth.urls')),
]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_DIR)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_DIR)

请帮忙 :)

干杯!


{% static 'images/parallax/home/9.jpg' %} 会生成什么URL?打开此URL时会得到哪种响应? - Ivan Starostin
页面未找到(404) 请求的URL:http://127.0.0.1:8000/Spaces/images/parallax/home/9.jpg - LeCoda
STATICFILES_DIRS和STATIC_URL的值是什么?你运行了collectstatic吗? - Ivan Starostin
由于使用了static函数和STATIC_URL='/static/'的值,给定的配置将导致127.0.0.1:8000/static/images/parallax/home/9.jpg。我猜想您没有运行collectstatic并且正在尝试访问位于Spaces应用程序子文件夹内的图像。这正确吗? - Ivan Starostin
你是在运行 DEBUG = True 还是 DEBUG = False - ivissani
4个回答

3

请确保在您的HTML文件顶部编写此行:

{% load static %}

第二点是使用“:”来关闭你的div标签。
</div>

并且写入一些内容到div中或为您的div提供 'height' 属性:

<div class="full-screen force-full-screen" style="background: url('{% static 'images/parallax/home/9.jpg' %}') center center no-repeat; background-size: cover;height: 100px;">

第三点:请确保以下两行代码在你的settings.py文件中:
```python LANGUAGE_CODE = 'zh-hans' USE_TZ = False ```
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_URL = '/static/'

希望这可以帮助到您。

1

在你的HTML文件(除了base.html)开头处使用{% load static %}代替{% load staticfiles %}

并确保在您的settings.py中可用。

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


1
使用{% load static from staticfiles %}。

0

我解决了这个问题。

我一直链接错误的文件夹。愚蠢的错误。

谢谢大家的帮助 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接