没有在Django中加载静态文件。获取404错误。settings.py中的静态直接定义看起来很正确

2024-10-03 21:35:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到以下错误

GEThttp://127.0.0.1:8000/static/bootstrap/css/bootstrap.min.cssnet::ERR_中止404(未找到) GEThttp://127.0.0.1:8000/static/bootstrap/css/bootstrap-grid.min.cssnet::ERR_中止404(未找到) GEThttp://127.0.0.1:8000/static/bootstrap/css/bootstrap-reboot.min.cssnet::ERR_中止404(未找到) . . . 等等

settings.py中的URL设置如下:

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

]

STATIC_ROOT = os.path.join(BASE_DIR, 'assets')

我已经在模板中输入了静态文件URL(home.html)

{%load static%}
<!DOCTYPE html>
<html  >
<head>
  <!-- meta data -->
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
  <link rel="shortcut icon" href="{% static 'images/logo4.png' %}" type="image/x-icon">
  <meta name="description" content="Website Builder Description">
  
  
  <title>home.html</title>

  <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
  <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap-grid.min.css' %}">
  <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap-reboot.min.css' %}">
  <link rel="stylesheet" href="{% static 'tether/tether.min.css' %}">
  <link rel="stylesheet" href="{% static 'dropdown/css/style.css' %}">
  <link rel="stylesheet" href="{% static 'animatecss/animate.min.css' %}">
  <link rel="stylesheet" href="{% static 'theme/css/style.css' %}">

我的文件夹结构如下:

enter image description here

enter image description here

有人能帮我解决这个问题吗

多谢各位


Tags: urlhtmldirlinkstaticbootstrapmincss
3条回答

在settings.py中,调试设置为TRUE

DEBUG = True

我把所有的静态文件都放在“static”文件夹中(我已经验证了static filder中的文件路径,按顺序排列),所以Django应该找到静态文件

下面是my templates/home.html的完整代码

{%load static%}
<!DOCTYPE html>
<html  >
<head>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="generator" content="Mobirise v4.12.4, mobirise.com">
  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
  <link rel="shortcut icon" href="{% static 'images/logo4.png' %}" type="image/x-icon">
  <meta name="description" content="Website Builder Description">
    
  <title>home.html</title>

  <link rel="stylesheet" href="{% static 'web/assets/mobirise-icons/mobirise-icons.css' %}">  
  <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
  <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap-grid.min.css' %}">
  <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap-reboot.min.css' %}">
  <link rel="stylesheet" href="{% static 'tether/tether.min.css' %}">
  <link rel="stylesheet" href="{% static 'dropdown/css/style.css' %}">
  <link rel="stylesheet" href="{% static 'animatecss/animate.min.css' %}">
  <link rel="stylesheet" href="{% static 'theme/css/style.css' %}">
  <link rel="preload" as="style" href="{% static 'mobirise/css/mbr-additional.css' %}"><link rel="stylesheet" href="assets/mobirise/css/mbr-additional.css" type="text/css">
  
  
  
</head>
<body>
  <section class="menu cid-s5iISe2c23" once="menu" id="menu1-8">

    

    <nav class="navbar navbar-expand beta-menu navbar-dropdown align-items-center navbar-fixed-top navbar-toggleable-sm bg-color transparent">
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <div class="hamburger">
                <span></span>
                <span></span>
                <span></span>
                <span></span>
            </div>
        </button>
        <div class="menu-logo">
            <div class="navbar-brand">
                <span class="navbar-logo">
                    <a href="home.html">
                         <img src="{% static 'images/logo-1-478x122.png' %}" alt="Mobirise" title="" style="height: 3.8rem;">
                         
                    </a>
                </span>
                
            </div>
        </div>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav nav-dropdown nav-right" data-app-modern-menu="true"><li class="nav-item"><a class="nav-link link text-black display-4" href="https://mobirise.co" aria-expanded="true">
                        
                        About Us
                    </a></li></ul>
            
        </div>
    </nav>
</section>

<section class="engine"><a href="https://mobirise.info/o">free portfolio website templates</a></section><section class="header1 cid-s5hTifxxmG" id="header16-6">

    

    

    <div class="container">
        <div class="row justify-content-md-center">
            <div class="col-md-10 align-center">
                
                <h3 class="mbr-section-subtitle mbr-light pb-3 mbr-fonts-style display-2">Work and select</h3>
                
                
            </div>
        </div>
    </div>

</section>

<section class="features3 cid-s5hXWwfo5o" id="features3-7">

    

    
    <div class="container">
        <div class="media-container-row">
            <div class="card p-3 col-12 col-md-6">
                <div class="card-wrapper">
                    
                    <div class="card-box">
                        <h4 class="card-title mbr-fonts-style display-5">
                            Engineers</h4>
                        <p class="mbr-text mbr-fonts-style display-4">Work And many more..</p>
                    </div>
                    <div class="mbr-section-btn text-center"><a href="https://mobirise.co" class="btn btn-success display-4">Sign up or Login</a></div>
                </div>
            </div>

            <div class="card p-3 col-12 col-md-6">
                <div class="card-wrapper">
                    
                    <div class="card-box">
                        <h4 class="card-title mbr-fonts-style display-5">
                            Companies and recruiters</h4>
                        <p class="mbr-text mbr-fonts-style display-4">Select and more...<br><br><br><br><br>
                        </p>
                    </div>
                    <div class="mbr-section-btn text-center"><a href="https://mobirise.co" class="btn btn-primary display-4">
                            Sign up or Login</a></div>
                </div>
            </div>

            

            
        </div>
    </div>
</section>


  <script src="{% static 'web/assets/jquery/jquery.min.js' %}"></script>
  <script src="{% static 'popper/popper.min.js' %}"></script>
  <script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
  <script src="{% static 'tether/tether.min.js' %}"></script>
  <script src="{% static 'dropdown/js/nav-dropdown.js' %}"></script>
  <script src="{% static 'dropdown/js/navbar-dropdown.js' %}"></script>
  <script src="{% static 'touchswipe/jquery.touch-swipe.min.js' %}"></script>
  <script src="{% static 'viewportchecker/jquery.viewportchecker.js' %}"></script>
  <script src="{% static 'smoothscroll/smooth-scroll.js' %}"></script>
  <script src="{% static 'theme/js/script.js' %}"></script>
  
  
  <input name="animation" type="hidden">
  </body>
</html>

有关加载的代码和网页,请参阅以下屏幕截图:

enter image description here

您设置:

STATIC_ROOT = os.path.join(BASE_DIR, 'assets')

这意味着,django将在资产中找到静态文件,如png、jpg、css、js

但你也设定了:

STATICFILES_DIR = [
    os.path.join(BASE_DIR, 'static'),

]

这意味着,django还将在静态中找到静态文件,如果在资产中找不到文件

因此,如果您确定静态文件位于其中一个文件夹中,您可以检查以下设置:


DEBUG = True

如果将调试设置为False,django的应用服务器将不会提供静态文件API

Django document告诉您如何部署静态文件,使用nginx,uwsgi就可以了

另外,您可以使用serve在url.py中获取它(在django.views.static中不建议使用这种方式)

import mimetypes
import posixpath
from pathlib import Path
from django.http import (
    FileResponse, Http404, HttpResponseNotModified
)
from django.conf import settings
from django.contrib import admin
from django.urls import path, re_path,include
from django.utils._os import safe_join
from django.utils.http import http_date
from django.utils.translation import gettext as _
from django.views.static import directory_index, was_modified_since


def re_serve(request, path, document_root=None, show_indexes=False):
    path = posixpath.normpath(path).lstrip('/')
    fullpath = Path(safe_join(document_root, path))
    if fullpath.is_dir():
        if show_indexes:
            return directory_index(path, fullpath)
        raise Http404(_("Directory indexes are not allowed here."))
    if not fullpath.exists():
        raise Http404(_('“%(path)s” does not exist') % {'path': fullpath})
    # Respect the If-Modified-Since header.
    statobj = fullpath.stat()
    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                              statobj.st_mtime, statobj.st_size):
        return HttpResponseNotModified()
    content_type, encoding = mimetypes.guess_type(str(fullpath))
    content_type = content_type or 'application/octet-stream'
    if path.split(".")[-1] == "js":
        content_type = "text/javascript" # I change it,the source code is different
    response = FileResponse(fullpath.open('rb'), content_type=content_type)
    response["Last-Modified"] = http_date(statobj.st_mtime)
    if encoding:
        response["Content-Encoding"] = encoding
    return response


urlpatterns = [
    path('admin/', admin.site.urls),
]

if not settings.DEBUG:
    urlpatterns += [
        re_path(r'^static/(?P<path>.*)$', re_serve, {'document_root': settings.STATIC_ROOT}, name='static'),
    ]

如果您确定,两个静态文件都在正确的文件夹中,并将DEBUG设置为True,可能是由于其他错误,请显示更多代码

STATICFILES\u DIR不正确,它是STATICFILES\u DIRS(DIR结尾带有一个S,因此它必须是复数)
https://docs.djangoproject.com/en/3.1/ref/settings/#std:setting-STATICFILES_DIRS

相关问题 更多 >