首页 > 解决方案 > 没有找到和加载 django 静态文件

问题描述

使用 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)

还有 urlpatternssales

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'.

我也收到了这个错误

在此处输入图像描述

我已经多次重新启动服务器。

标签: pythoncssdjangodjango-staticfilesstatic-files

解决方案


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

  • 对于 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,
    ...
}

推荐阅读