django的样式表未在Docker中运行(在venv中工作)

gk7wooem  于 2023-11-17  发布在  Docker
关注(0)|答案(1)|浏览(107)

我一直在为这个问题烦恼。每次加载页面时,我都会收到以下错误消息:

listings:20 Refused to apply style from 'http://localhost:8000/static/meltexapp/main.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

字符串
这是我的文件结构:

meltex
-settings.py
[...]
meltexapp
-static
--meltexapp.css
-templates
--nav.html
Dockerfile
docker-compose.yaml
[...]


settings.py:

from pathlib import Path
import environ
import os

env = environ.Env()
environ.Env.read_env()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-raa_)uczfns2bd8y&-vl5cg0gvyrk29%sy641kwem$809elt2g"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []

AUTH_USER_MODEL = "meltexapp.User"
# Application definition

INSTALLED_APPS = [
    "meltexapp",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "bootstrap5",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "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",
]

ROOT_URLCONF = "meltex.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",
                "django.template.context_processors.static",
            ],
        },
    },
]

WSGI_APPLICATION = "meltex.wsgi.application"

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

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": env("DATABASE_NAME"),
        "USER": env("DATABASE_USER"),
        "PASSWORD": env("DATABASE_PASS"),
        "HOST": env("DATABASE_HOST"),
        "PORT": env("DB_PORT"),
    }
}

LOGIN_REDIRECT_URL = "/"

# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True

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

STATIC_URL = "static/"
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"


Dockerfile

ARG PYTHON_VERSION=3.9.6
FROM python:${PYTHON_VERSION}-slim as base

# Prevents Python from writing pyc files.
ENV PYTHONDONTWRITEBYTECODE=1

# Keeps Python from buffering stdout and stderr to avoid situations where
# the application crashes without emitting any logs due to buffering.
ENV PYTHONUNBUFFERED=1

WORKDIR /app

# Create a non-privileged user that the app will run under.
# See https://docs.docker.com/go/dockerfile-user-best-practices/
ARG UID=10001
RUN adduser \
  --disabled-password \
  --gecos "" \
  --home "/nonexistent" \
  --shell "/sbin/nologin" \
  --no-create-home \
  --uid "${UID}" \
  appuser

# Download dependencies as a separate step to take advantage of Docker's caching.
# Leverage a cache mount to /root/.cache/pip to speed up subsequent builds.
# Leverage a bind mount to requirements.txt to avoid having to copy them into
# into this layer.
RUN --mount=type=cache,target=/root/.cache/pip \
  --mount=type=bind,source=requirements.txt,target=requirements.txt \
  python -m pip install -r requirements.txt

# Switch to the non-privileged user to run the application.
USER appuser

# Copy the source code into the container.
COPY . .

# Expose the port that the application listens on.
EXPOSE 8000

# Run the application.
CMD gunicorn 'meltex.wsgi' --bind=0.0.0.0:8000


docker-compose.yaml

services:
  server:
    volumes:
      - ./meltexapp/static:/app/meltexapp/static
    build:
      context: .
    ports:
      - 8000:8000
    environment:
      - DATABASE_HOST=${DATABASE_HOST}
      - DB_PORT=${DB_PORT}
      - DATABASE_USER=${DATABASE_USER}
      - DATABASE_PASS=${DATABASE_PASS}
      - DATABASE_NAME=${DATABASE_NAME}
    depends_on:
      db:
        condition: service_healthy
  db:
    image: postgres
    restart: always
    user: postgres
    volumes:
      - db-data:/var/lib/postgresql/data
    environment:
      - POSTGRES_PASSWORD=${DATABASE_PASS}
    ports:
      - "5432:5432"
    healthcheck:
      test: [ "CMD", "pg_isready" ]
      interval: 10s
      timeout: 5s
      retries: 5
volumes:
  db-data:


nav.html

<!DOCTYPE html>
{% load static %}
<link rel="stylesheet" href="{% static 'meltexapp/main.css' %}">
<!-- <nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class="container-fluid">
    <a class="navbar-brand" href="/">Home</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup"
      aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
      <div class="navbar-nav">
        <a class="nav-link active" aria-current="page" href="/listings">Listings</a>
        <a class="nav-link active" href="/listings/add_listing">Add Listing</a>
        <a class="nav-link active" href="/listings/my_listings">My Listing</a>
      </div>
    </div>
  </div>
</nav> -->
<div class="d-flex flex-row bd-highlight">
  <div class="page-wrap min-vw-100">
    <div class="bd-highlight">
      <div class="d-flex flex-column flex-shrink-0 p-3 text-white bg-dark" id="sidebar"
        style="width: 220px; height: 100vh">
        <a href="/" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-white text-decoration-none">
          <svg class="bi me-2" width="40" height="32">
            <use xlink:href="#bootstrap"></use>
          </svg>
          <span class="fs-4">MeltEx</span>
        </a>
        <hr>
        <ul class="nav nav-pills flex-column mb-auto">
          <li class="nav-item">
            <a href="/" class="nav-link text-white" aria-current="page">
              <svg class="bi me-2" width="16" height="16">
                <use xlink:href="/"></use>
              </svg>
              Home
            </a>
          </li>
          <li>
            <a href="/listings" class="nav-link text-white">
              <svg class="bi me-2" width="16" height="16">
                <use xlink:href="#speedometer2"></use>
              </svg>
              Listings
            </a>
          </li>
          <li>
            <a href="/listings/my_listings" class="nav-link text-white">
              <svg class="bi me-2" width="16" height="16">
                <use xlink:href="#table"></use>
              </svg>
              My Listings
            </a>
          </li>
          <li>
            <a href="/listings/add_listing" class="nav-link text-white">
              <svg class="bi me-2" width="16" height="16">
                <use xlink:href="#grid"></use>
              </svg>
              Add Listing
            </a>
          </li>
        </ul>
        <hr>
        <div class="dropdown">
          <a href="#" class="d-flex align-items-center text-white text-decoration-none dropdown-toggle"
            id="dropdownUser1" data-bs-toggle="dropdown" aria-expanded="false">
            <i class="fa-solid fa-user ms-3 me-3" style="color: #98aac8;"></i>
            <strong>{{user.username}}</strong>
          </a>
          <ul class="dropdown-menu dropdown-menu-dark text-small shadow" aria-labelledby="dropdownUser1">
            <li><a class="dropdown-item" href="/listings/my_listings">My Listings</a></li>
            <li>
              <hr class="dropdown-divider">
            </li>
            <li><a class="dropdown-item" href="/accounts/logout/">Sign out</a></li>
          </ul>
        </div>
      </div>
    </div>
    <div class="p-2 navbar-pad">
      <script src="/docs/5.0/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
        crossorigin="anonymous"></script>


由于这是在我的虚拟环境中工作,我只能假设有一些与docker有关的东西,我错过了,任何帮助都将不胜感激!
编辑-我还注意到甚至django-admin css也没有加载:

Refused to apply style from 'http://localhost:8000/static/admin/css/dashboard.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.


不确定这里会发生什么?

s3fp2yjn

s3fp2yjn1#

所以这个问题与gunicorn有关,不太确定问题是什么,但由于某种原因,当你通过dockerfile运行它时,没有一个静态文件加载:

CMD gunicorn 'meltex.wsgi' --bind=0.0.0.0:8000

字符串
这是docker设置中给我的默认值。我简单地将其更改为:

CMD python3 manage.py runserver 0.0.0.0:8000


而且成功了!如果有人知道为什么很高兴有你加入这个!

相关问题