我无法在 django 中使用“静态”模板导入 css 文件

Posted

技术标签:

【中文标题】我无法在 django 中使用“静态”模板导入 css 文件【英文标题】:I can't import css file using 'static' template in django 【发布时间】:2021-03-21 04:33:23 【问题描述】:

我正在尝试使用 Django 开发我的第一个 Web 应用程序,所以网站看起来像这样:

Site without changes

另一方面,我想应用一些更改并将其放入名为:cabecalho.css 的 CSS 文件中

cabecalho.css 文件(包含更改)- 路径:(project/static/css/cabecalho.css):

     <style>
       body 
        font-family: Segoe UI;
       
       .logo 
        float: left;
       
       .logo img 
        width: 250px;
        padding: 20px;
       
       .menu 
        float: right;
        padding: 40px;
        font-size: 15pt;
       
       .menu a 
        margin-left: 15px;
        margin-right: 15px;
       
       .bemvindo 
        clear: both;
        padding: 0 20px;
       

       </style>

这些更改使网站看起来像这样:

Site with CSS changes

在我的名为 cabecalho.html 的 HTML 文件中,我尝试使用行代码导入:

1 try: <link rel="stylesheet" href=% static 'css/cabecalho.css' %/>

2 try: <link rel="stylesheet" type="text/css" href=% static "css/cabecalho.css" %/>

3 try: <link rel="stylesheet" type="text/css" href="css/cabecalho.css"> 

这样,什么都不会发生!

HTML 文件 (cabecalho.html) - 路径:(project/templates/django/cabecalho.html):

<!DOCTYPE html>

% load static % <!-- Nova linha que carrega os arquivos estáticos -->

<html>

  <head>
    <title>Django Form Exemplo</title>
             <link rel="stylesheet" href=% static 'css/cabecalho.css' %/>
    </head>

    <body>
     <div class='logo'>
       <img src="% static "images/logo.png" %"  />
     </div>

     <div class='menu'>
       <a href="/app/sobre/">Sobre</a>
       <a href="/app/sair/">Sair</a>
     </div>

     <div class='bemvindo'>
       <h2>Bem vindo ao nosso Site Django Exemplo!</h2>
     </div>

    </body>

</html>

Obs:如果我删除这一行并添加如下 CSS 内容,就会发生变化。

<!DOCTYPE html>

% load static % <!-- Nova linha que carrega os arquivos estáticos -->

<html>

  <head>
    <title>Django Form Exemplo</title>
                          <style>
               body 
                font-family: Segoe UI;
               
               .logo 
                float: left;
               
               .logo img 
                width: 250px;
                padding: 20px;
               
               .menu 
                float: right;
                padding: 40px;
                font-size: 15pt;
               
               .menu a 
                margin-left: 15px;
                margin-right: 15px;
               
               .bemvindo 
                clear: both;
                padding: 0 20px;
               

               </style>

    </head>

    <body>
     <div class='logo'>
       <img src="% static "images/logo.png" %"  />
     </div>

     <div class='menu'>
       <a href="/app/sobre/">Sobre</a>
       <a href="/app/sair/">Sair</a>
     </div>

     <div class='bemvindo'>
       <h2>Bem vindo ao nosso Site Django Exemplo!</h2>
     </div>

    </body>

</html>

我曾经尝试过的问题:

<link rel="stylesheet" type="text/css" href="style.css"> isn't work

import css using 'static' template in Django

更多信息:

views.py (app/views.py):

from django.shortcuts import render
from django.http import HttpResponse


def index(request):


    
    return render(request, 'django/cabecalho.html')

settings.py(项目/settings.py):

"""
Django settings for project project.

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

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

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

from pathlib import Path
import os

# 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/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#w1odqj&ebl80i3)@m=y5uq@q+rf!+7bk6!&qt@0h8b1#xfy8g'

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

ALLOWED_HOSTS = []


# Application definition

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

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 = 'project.urls'

TEMPLATES = [
    
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(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',
            ],
        ,
    ,
]

TEMPLATE_DIRS = ('C:/Users/Leonardo/microblog/project/templates',)

WSGI_APPLICATION = 'project.wsgi.application'


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

DATABASES = 
    'default': 
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    



# Password validation
# https://docs.djangoproject.com/en/3.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/3.1/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/3.1/howto/static-files/

STATIC_PATH = os.path.join(BASE_DIR, 'static')  # concatena a pasta static a variavel instanciada base_dir que aponta para a raiz do projeto

STATIC_URL = '/static/' # chamada que terá no browswer para a pasta de arquivos estaticos

STATICFILES_DIRS = (
    STATIC_PATH,
)

文件夹:

enter image description here

【问题讨论】:

您如何为您的应用程序提供服务? Daniel,我编写了一个 CSS 代码,其中包含一些要导入 HTML 文件的设置。然后我有一个代码视图: def index(request): return render(request, 'django/cabecalho.html') 【参考方案1】:

你忘记了 href 属性 &lt;link rel="stylesheet" href="% static 'css/cabecalho.css' %"/&gt; 的外部双引号

【讨论】:

在您的浏览器控制台中显示与 cabecalho.css 相关的任何错误

以上是关于我无法在 django 中使用“静态”模板导入 css 文件的主要内容,如果未能解决你的问题,请参考以下文章

Django使用模板后无法找到静态资源文件

使用 jinja2 作为 django 模板引擎时出错:无法导入名称“环境”

Django:无法从 DigitalOcean Droplet 上的模板加载静态文件

Django 如何使用带有静态/模板的 npm 模块

模板语法错误无法解析剩余部分:来自“静态(“images/logo.png”)”的“(“images/logo.png”)”。在 django-jinja 模板中?

Django静态图像文件无法加载资源