Django模板不包含静态css文件?

bzzcjhmw  于 2023-05-19  发布在  Go
关注(0)|答案(1)|浏览(167)

我有一个简单的django应用程序,我试图加载一个静态css文件,但它似乎不工作。我可以在浏览器中导航到CSS文件。
下面是我的模板文件的开头:

{% extends '_base.html' %}

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'datasets/css/styles.css' %}">

{% block content %}
  <div class="container">
    <div class="row">
      <div class="col-md-12">
        <h1 class="mb-4">Datasets</h1>
        <table class="table">
          <thead>
            <tr>
              <th>Title</th>
              <th>Description</th>
            </tr>
          </thead>
          <tbody>
            {% for dataset in datasets %}
              <tr>
                <td>

这是我的网站settings.py:

"""
from pathlib import Path
from environs import Env

env = Env()
env.read_env()

# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "whitenoise.runserver_nostatic",  # new
    "django.contrib.staticfiles",
    "django.contrib.sites",
    # Third-party
    "crispy_forms",
    "crispy_bootstrap5",
    "allauth",
    "allauth.account",
    "debug_toolbar",
    # Local
    "accounts.apps.AccountsConfig",
    "pages.apps.PagesConfig",
    "books.apps.BooksConfig",
    'datasets'
]

MIDDLEWARE = [
    "django.middleware.cache.UpdateCacheMiddleware",
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",  # new
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "debug_toolbar.middleware.DebugToolbarMiddleware",
    "django.middleware.cache.FetchFromCacheMiddleware",
]

ROOT_URLCONF = "django_project.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "templates"],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "django_project.wsgi.application"

# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
   "default": env.dj_db_url("DATABASE_URL", default="postgres://postgres:postgres@db/postgres")
}

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

STATIC_URL = "/static/"
STATICFILES_DIRS = [BASE_DIR / "static"]
print(f'Static files dirs: {STATICFILES_DIRS}')
#STATICFILES_DIRS = [BASE_DIR / ]
STATIC_ROOT = BASE_DIR / "staticfiles"
#STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage"
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"

这是我的网站urls.py:

from django.urls import path
from .views import DatasetListView, DatasetDetailView
#from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django.conf.urls.static import static
from . import views
import uuid

urlpatterns = [
    path('browse/', DatasetListView.as_view(), name='dataset_browse'),
    path('datasets/<uuid:pk>/', DatasetDetailView.as_view(), name='dataset_detail'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

#urlpatterns += staticfiles_urlpatterns()

以下是我的(相关)目录结构:

.
├── datasets
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   ├── urls copy working1a.py
│   ├── urls.py
│   ├── views copy working1a.py
│   └── views.py
├── django_project
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── requirements.txt
├── static
│   ├── covers
│   │   ├── dfp.jpg
│   │   ├── dfp_I4SCkr4.jpg
│   │   ├── dfp_KUn7MFY.jpg
│   │   └── dfp_MYQvv1k.jpg
│   ├── css
│   │   └── base.css
│   ├── datasets
│   │   └── css
│   │       └── styles.css
│   ├── images
│   │   └── dfp.jpg
│   └── js
│       └── base.js

我做错了什么?!?
我试图垂直居中的内容,当我检查页面时,我可以看到base.css,但我没有看到对styles.css文件的引用,内容没有居中。
我试过使用os join设置静态目录,如:STATICFILES_DIRS = [ os.path.join(BASE_DIR,'/static')]
编辑以add _base.html:

{% load static %}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>{% block title %}Bookstore{% endblock title %}</title>
  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <!-- CSS -->
  <link rel="stylesheet" href="{% static 'css/base.css' %}">
</head>
<body>
  <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
    <div class="container-fluid">
      <a class="navbar-brand" href="{% url 'home' %}">Bookstore</a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarCollapse">
        <ul class="navbar-nav me-auto mb-2 mb-md-0">
          <li class="nav-item">
            <a class="nav-link" href="{% url 'book_list' %}">Books</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="{% url 'about' %}">About</a>
          </li>
          {% if user.is_authenticated %}
          <li class="nav-item">
            <a class="nav-link" href="{% url 'account_logout' %}">Log Out</a>
          </li>
          {% else %}
          <li class="nav-item">
            <a class="nav-link" href="{% url 'account_login' %}">Log In</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="{% url 'account_signup' %}">Sign Up</a>
          </li>
          {% endif %}
        </ul>
        <form class="d-flex" action="{% url 'search_results' %}" method="get">
          <input class="form-control me-2" type="search" name="q" placeholder="Search" aria-label="Search" >
          <button class="btn btn-outline-success" type="submit">Search</button>
        </form>
      </div>
    </div>
  </nav>
  <div class="container">
    {% block content %}
    {% endblock content %}
  </div>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
  <!-- JavaScript -->
  <script src="{% static 'js/base.js' %}"></script>
</body>
</html>
z3yyvxxp

z3yyvxxp1#

错误原因

模板继承只能 * 覆盖 * 祖先中定义的块。它不能添加全新的块-模板引擎不知道它应该出现在最终页面的哪里。
你有这个块:

<div class="container">
    {% block content %}
    {% endblock content %}
  </div>

Django知道把继承模板中的block content代码放在哪里-在这个div中。
link

{% extends '_base.html' %}

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'datasets/css/styles.css' %}">

从继承的模板中获取的数据并不位于任何定义的 * 块 * 中,即使您编写了类似于

{% block styles %}
<link rel="stylesheet" type="text/css" href="{% static 'datasets/css/styles.css' %}">
{% endblock %}

Django仍然不知道这个块应该位于哪里-它没有Map到_base.html中的任何地方。* 在块“内容”上面的某个地方 * -不,它不工作。

溶液

要修复此问题,请在_base.html中定义额外的块,以便继承的模板可以覆盖它:
_base.html

<head>
  ...
  <!-- CSS -->
  <link rel="stylesheet" href="{% static 'css/base.css' %}">
  {% block styles %}
  {% endblock %}
</head>
...
  <div class="container">
    {% block content %}
    {% endblock content %}
  </div>
...

任何继承模板

{% extends '_base.html' %}

{% block styles %}
<link rel="stylesheet" type="text/css" href="{% static 'datasets/css/styles.css' %}">
{% endblock styles %}

{% block content %}
<p>My content</p>
{% endblock content %}

相关问题