【问题标题】:Django not loading static files (Pycharm)Django 不加载静态文件(Pycharm)
【发布时间】:2017-11-08 12:04:13
【问题描述】:

我正在做一个需要加载 CSS 样式表和徽标文件的项目。但是我的 Django 服务器在加载这些文件时也返回 404 资源未找到。我已经检查了其他类似的问题,但没有一个使用该格式来指定我使用的静态文件。 这是我正在使用的 html 代码

{% block stylesheets %}
    <link rel="stylesheet" type="text/css" href="/static/Emu86/style.css">
{% endblock stylesheets %}

这是我的 settings.py 文件:

    """
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 1.9.1.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/



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


# Application definition

INSTALLED_APPS = [
    'Emu86',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',

]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'mysite.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.9/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/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] \
                %(message)s",
                'datefmt': "%d%b%Y %H:%M:%S"
         },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'Emu86.log',
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'propagate': True,
            'level': 'DEBUG',
        },
        'Emu86': {
            'handlers': ['file'],
            'level': 'DEBUG',
        },
    },
}

项目结构:

Emu86/
  mysite/
      static/ 
        Emu86/

【问题讨论】:

  • 你应该展示你的应用的文件夹结构,主要是你的静态文件夹
  • 在你的设置文件中说是 django 1.9.1
  • 这有什么不同吗?我正在使用 Pycharm 运行它
  • 你的文件夹结构很奇怪:mysite是项目文件夹还是app文件夹?
  • 是app文件夹,如何识别?它有 settings.py

标签: python css django pycharm


【解决方案1】:
{% load static %}    
{% block stylesheets %}
        <link rel="stylesheet" type="text/css" href="{% static "Emu86/style.css"%}">
{% endblock stylesheets %}

我猜路径必须如上

【讨论】:

  • 这给出了一个错误:第 10 行的块标记无效:'static',预期为 'endblock'。您是否忘记注册或加载此标签?
  • 哎呀,我以为你正在导入静态模板,但我添加了一个可能有用的编辑
【解决方案2】:

您必须在模板顶部加载 static 模板标签,然后使用它来获取静态文件的 url:

{% load static %}

{% block stylesheets %}
    <link rel="stylesheet" type="text/css" href="{% static "Emu86/style.css" %}">
{% endblock stylesheets %}

编辑

您必须在您的 settings.py 文件中定义 STATICFILES_DIRS 常量以从项目目录中查找您的静态文件夹:

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "mysite", "static"),
]

【讨论】:

    【解决方案3】:

    首先将此'django.template.context_processors.static' 添加到您的 context_processors 数组中。然后在你的模板文件中使用像这样的静态文件
    &lt;link rel="stylesheet" type="text/css" href="{{STATIC_URL}}Emu86/style.css"&gt;

    ** 不要忘记将所有静态文件放在静态文件夹中。

    【讨论】:

      【解决方案4】:

      你需要在setting.py中做一些修改

      添加

      STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ]

      低于 BASE_DIR....

      希望它有效

      【讨论】:

      • 在所有这些方法中效果很好,非常感谢
      猜你喜欢
      • 2019-01-21
      • 2017-11-08
      • 1970-01-01
      • 2019-08-24
      • 2012-04-30
      • 2020-12-10
      • 2013-12-09
      • 2021-11-20
      • 2021-05-30
      相关资源
      最近更新 更多