1
votes

Les fichiers statiques ne se chargent pas dans Django. Obtenez l'erreur 404. La définition de directry statique dans settings.py semble correcte

J'obtiens l'erreur suivante;

GET http://127.0.0.1:8000/static/bootstrap/css/bootstrap.min.css net :: ERR_ABORTED 404 (Not Found) GET http://127.0.0.1:8000/static/bootstrap/css/bootstrap- grid.min.css net :: ERR_ABORTED 404 (Not Found) GET http://127.0.0.1:8000/static/bootstrap/css/bootstrap-reboot.min.css net :: ERR_ABORTED 404 (Not Found). . . bientôt...

Le paramètre d'URL dans settings.py est le suivant;

{%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' %}">

J'ai entré les URL de fichier statique dans le modèle (home.html);

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

]

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

Ma structure de dossiers comme suit:

entrez la description de l'image ici

entrez la description de l'image ici

Quelqu'un peut-il m'aider à résoudre le problème?

Merci


0 commentaires

3 Réponses :


0
votes

Vous définissez:

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'),
    ]

Ce qui signifie que django trouvera le fichier statique, comme png, jpg, css, js, dans les assets.

Mais vous définissez également:

DEBUG = True

Ce qui signifie que django trouvera également le fichier statique, en statique, s'il ne peut pas trouver le fichier dans les assets.

Donc, si vous êtes sûr que le fichier statique se trouve dans un dossier d'entre eux, vous pouvez vérifier le paramètre concernant:

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

]

Si vous définissez DEBUG sur False , le serveur d'applications de django ne fournira pas d'apis de fichiers statiques.

Le document Django vous indique comment déployer des fichiers statiques, utilisez nginx, uwsgi est OK.

En outre, vous pouvez utiliser serve pour l'obtenir dans urls.py (pas suggérer de cette façon, dans django.views.static)

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

Si vous êtes sûr, les deux fichiers statiques sont dans le bon dossier et définissez le DEBUG sur True , peut provenir d'une autre erreur, affichez plus de code s'il vous plaît.


0 commentaires

0
votes

Dans settings.py, DEBUG est défini sur TRUE

{%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>

J'ai tous les fichiers statiques dans le dossier «statique» (j'ai vérifié le chemin du fichier dans le fichier statique, c'est dans l'ordre), donc Django devrait trouver les fichiers statiques.

Ci-dessous le code complet de mes templates / home.html

DEBUG = True

Reportez-vous à la capture d'écran ci-dessous pour le code et la page Web chargés:

entrez la description de l'image ici


1 commentaires

Quelle serait l'erreur / le problème dans la configuration ci-dessus?



0
votes

STATICFILES_DIR n'est pas correct, il est STATICFILES_DIRS (DIR avec un S à la fin donc il doit être au pluriel également)
https://docs.djangoproject.com/en/3.1/ref/settings/#std:setting-STATICFILES_DIRS


0 commentaires