【问题标题】:django static files are not being found and loaded没有找到和加载 django 静态文件
【发布时间】:2021-09-04 11:25:30
【问题描述】:

使用 django v2.2.1

我有一个给定的项目目录。结构:

在根项目目录中。 static 目录中有一些静态文件。

base.html 文件中,

{% load static %}
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- favicon --> 
    <link rel="shortcut icon" href="{% static 'favicon.ico' %}" />    

    <!-- Dropzone js -->
    <link rel="stylesheet" href="{% static 'dropzone.css' %}">
    <script src="{% static 'dropzone.js' %}" defer></script>

    <!-- Custom js & css -->
    <link rel="stylesheet" href="{% static 'style.css' %}">
    .
    . 

这是settings.py 文件:

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIR = [
    os.path.join(BASE_DIR, 'static'),
    os.path.join(BASE_DIR, 'sales', 'static'),
]

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

urls.py

from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls), 
    path('', include('sales.urls', namespace='sales')),   
    path('reports/', include('reports.urls', namespace='reports'))   
] 

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

还有sales的urlpatterns

urlpatterns = [
    path('', home_view, name='home'),
    path('sales/', SaleListView.as_view(), name='list'),
    path('sales/<pk>/', SaleDetailView.as_view(), name='detail'),
]

试过

$ python manage.py findstatic style.css
No matching file found for 'style.css'.

我也遇到了这个错误

我已经多次重启服务器了。

【问题讨论】:

  • 您是否已将静态网址添加到您的网址格式中?参考Serving static files during development
  • @AbdulAzizBarkat 是的。忘记在帖子中提及了..现在更新了
  • 您能展示一下sales.urls 的模式吗?我相信其中之一可能与您的静态网址等匹配。
  • 再次更新帖子

标签: python css django django-staticfiles static-files


【解决方案1】:

将以下内容添加到 settings.py 中的 TEMPLATES 应该对您的情况有所帮助:

  • 对于 Django3.x
TEMPLATES = [
 {
    ...
    'DIRS': [BASE_DIR / 'templates'],
    'APP_DIRS': True,
    ...
}
  • 对于 Django2.x
import os
...
TEMPLATES = [
 {
    ...
    'DIRS': os.path.join(BASE_DIR, 'templates'),
    'APP_DIRS': True,
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-07
    • 2020-01-08
    • 2019-05-04
    • 2021-07-22
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多