简体   繁体   English

Django未加载静态文件(Pycharm)

[英]Django not loading static files (Pycharm)

I am working on a project which requires loading on a CSS stylesheet and a logo file. 我正在做一个需要在CSS样式表和徽标文件上加载的项目。 But my Django server also returns 404 resource not found while loading these files. 但是我的Django服务器在加载这些文件时也返回了404资源找不到的信息。 I have checked other questions like this but none of them is using the format to specify static files I used. 我已经检查了其他类似问题,但是没有一个问题使用该格式指定我使用的静态文件。 This is the html code i am using 这是我正在使用的html代码

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

This is my settings.py file: 这是我的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',
        },
    },
}

Project Structure: 项目结构:

Emu86/
  mysite/
      static/ 
        Emu86/

you need to do some changes in setting.py 您需要在setting.py中进行一些更改

Add

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

below BASE_DIR.... 低于BASE_DIR...。

hope it works 希望它能工作

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

I guess the path has to be as above 我想路径必须如上所述

You have to load the static template tag at the top of your template and then use it for getting the url to your static files: 您必须在模板顶部加载static模板标记,然后使用它来获取静态文件的网址:

{% load static %}

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

edit 编辑

You have to define in your settings.py file the STATICFILES_DIRS constant to look for your static folder from the project directory: 您必须在settings.py文件中定义STATICFILES_DIRS常量,以从项目目录中查找您的静态文件夹:

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

First of all add this 'django.template.context_processors.static' to your context_processors array. 首先,将此'django.template.context_processors.static'添加到context_processors数组中。 And then in your template file use static file like this 然后在您的模板文件中使用这样的静态文件
<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}Emu86/style.css">

** Do not forget to place all your static file in your static folder. **不要忘记将所有静态文件放在静态文件夹中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM