Django:无法更新CSS更改 [英] Django: cannot update css changes

查看:144
本文介绍了Django:无法更新CSS更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行服务器后,我的页面没有显示我在CSS文件中所做的更新。



我的导航栏无法识别CSS规则: .navbar-bg {background-color:black;} (我刚刚测试了此规则)。



但是,如果我粘贴相同的 HTML CSS 代码在像CodePen这样的网站中有效(我的导航栏显示黑色背景)。



https://codepen.io / ogonzales / pen / KbKzQo



如果我从PC的目录中运行HTML和CSS,也会发生同样的情况,因此我认为这与Django有关。



那会是什么?



我也尝试了这个其他答案:

  python manage.py collectstatic --noinput --clear 

从这里开始(无结果):





更新2:(settings.py)

  
perfectcushion项目的Django设置。

由django-admin startproject使用Django 2.1.3。生成。
$ b有关此文件的更多信息,请参见
https://docs.djangoproject.com/en/2.1/topics/settings/

有关设置的完整列表及其值,请参见
https://docs.djangoproject.com/en/2.1/ref/settings/


import os

#像这样在项目内部构建路径:os.path.join(BASE_DIR,...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__ file__)) )


#快速启动开发设置-不适合生产
#参见https://docs.django project.com/zh-CN/2.1/howto/deployment/checklist/

#安全警告:请将生产中使用的密钥保密!
SECRET_KEY ='^ _67&#r +(c +%pu& n + a%& dmxql ^ i ^ _ $ 0f69)mnhf @)zq-rbxe9z'

#安全警告:不要在生产中打开调试的情况下运行!
DEBUG =真

ALLOWED_HOSTS = []


#应用程序定义

INSTALLED_APPS = [
' django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django。 contrib.messages',
'django.contrib.staticfiles',
'shop',
'search_app',
'cart',
'stripe',
'order',
'crispy_forms',

]

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

模板= [
{
'BACKEND':'django.template.backends.django.DjangoTemplates',
'DIRS':[os.path.join(BASE_DIR,'templates'),
os.path.join(BASE_DIR,'shop','templates /'),
os.path.join(BASE_DIR,'search_app','templates /'),
os.path .join(BASE_DIR,'cart','templates /'),
os.path.join(BASE_DIR,'order','templates /'),]

'APP_DIRS' :正确,
'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',
'shop.context_processor.menu_links',
'购物车。 WGSG的context_processor.counter'
],
},
},
]

I_APPLICATION ='perfectcushion.wsgi.application'


#数据库
#https://docs.djangoproject.com/zh/2.1/ref/settings/#databases

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


#密码验证
#https://docs.djangoproject.com/cn /2.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',
},
]


#国际化
#https: //docs.djangoproject.com/zh-CN/2.1/topics/i18n/

LANGUAGE_CODE ='en-us'

TIME_ZONE ='UTC'

USE_I18N =真实

USE_L10N =真实

USE_TZ =真实


#静态文件(CSS,JavaScript,图像)
#https://docs.djangoproject.com/zh-CN/2.1/howto/static-files/

STATIC_URL ='/ static /'

STATIC_ROOT =操作系统.path.join(BASE_DIR,'staticfiles')

STATICFILES_DIRS =(
os.path.join(BASE_DIR,'static'),


MEDIA_URL ='/ media /'

MEDIA_ROOT = os.path.join(BASE_DIR,'static','media')


###条带设置###


STRIPE_PUBLISHABLE_KEY ='pk_test_N0ksyIuO5d1ulLDuoMlLiU26'

STRIPE_SECRET_KEY ='sk_test_fFHncrzOzBPS3XxDQM_TW_b



$ b

更新3



static 文件夹中创建 static_dirs ,然后更改以下内容:

 #STATICFILES_DIRS =(
#os.path.join(BASE_DIR,'static'),
#)

STATICFILES_DIRS =(
os.path.join(BASE_DIR,'static','static_dirs'),

然后执行 collecstatic 无效:

  manage.py@perfectcushion> collectstatic 
bash -cl / home / ogonzales / Escritorio / projects_envs / perfectcushion_env / bin / python /home/ogonzales/Escritorio/pycharm/helpers/pycharm/django_manage.py collectstatic / home / ogonzales / Escritorhion / per_proy
按文件夹模式跟踪文件:迁移

您已请求在设置中指定的目标
位置收集静态文件:

/主页/ ogonzales / Escritorio / web_proyects / perfectcushion / staticfiles

这将覆盖现有文件!
您确定要执行此操作吗?

键入是继续,或否取消:是

0将静态文件复制到'/ home / ogonzales / Escritorio / web_proyects / perfectcushion / staticfiles' 119未修改。

流程结束,退出代码为0

更新4:项目结构:



< img src = https://i.stack.imgur.com/G0v1h.png alt =在此处输入图片描述>

解决方案

  STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles')

STATIC_ROOT 应该是目的地文件夹,用于 collectstatic 命令。就是从源目录复制文件的地方。

  STATICFILES_DIRS =(
os.path.join(BASE_DIR,' static'),

STATICFILES_DIRS 列表来源文件夹,用于 collectstatic 。其他文件夹。因为将搜索INSTALLED_APPS 中任何应用程序中所有名为 static 的子文件夹docs.djangoproject.com/zh-CN/2.1/ref/contrib/staticfiles/#django-admin-collectstatic rel = nofollow noreferrer>默认情况下自动。这意味着-甚至是第三方应用,例如DRF或其他任何内容。



再次,在 STATICFILES_DIRS 中,应列出所有带有不是django项目应用程序的 / static / 子文件夹。例如。如果您在某处 / home / me / my_super_imgs / 并配置:

  STATIC_ROOT ='/ var / opt / prod / static /'
STATICFILES_DIRS =(
'/ home / me / my_super_imgs /',

您将在 /中拥有 my_super_imgs 的所有文件和子文件夹执行 collectstatic 后,var / opt / prod / static / 。以及 INSTALLED_APPS 中列出的所有应用程序的 / static / 子文件夹中的所有内容。



如果您有 shop / static / 文件夹-其内容将被收集到 staticfiles 默认情况下。



注意,您正在尝试在模板的 / static / url下加载静态文件,但目标文件夹中被命名为 staticfiles 。没关系,因为您已经配置了STATIC_ROOT和STATIC_URL,但可能会造成混淆,因为您还具有 / static / 文件夹。



另一件事:

 'DIRS':[os.path.join(BASE_DIR,'templates'),
os.path.join(BASE_DIR,'shop','templates /'),
os.path.join(BASE_DIR,'search_app','templates /'),
os.path。 join(BASE_DIR,'cart','templates /'),
os.path.join(BASE_DIR,'order','templates /'),]

'APP_DIRS':是的,

在此处停止列出您的 app dirs - APP_DIRS 已启用,这就足够了。



upd



为什么浏览器会不能反映CSS文件的更改?



服务器磁盘上的文件与客户端的呈现页面之间有许多级别的缓存。通过执行此技巧 href = {%static'css / custom.css'%}?20181209> (请参阅问题符号?),正如我在您的评论中提到的那样问题,您要更改完整的URL,并且它会强制重新加载CSS(或任何其他)文件,而物理文件名未更改。文件更改后,之后的更新日期。这是一个众所周知的把戏。该值可以是该文件的日期或哈希值。



此外,您可以引入模板标签,例如 {%my_css%} ,该模板标签将插入具有定义日期的静态文件名URL中的/ hash / build参数-为避免将此魔术参数复制到许多模板中。



现在,您可以手动测试带参数的css文件:




  • 更新css文件

  • 通过打开css文件url检查浏览器没有看到更改

  • 使用任何?parameter

  • 完成相同的URL,刷新文件内容


After running my server, my page doesn't show the updates that I've made in the CSS file.

My navbar won't recognize a css rule: .navbar-bg {background-color: black;} (i've just tested this rule).

However, If I paste this same HTML and CSS code in a site like CodePen it works (my navbar gets a black background).

https://codepen.io/ogonzales/pen/KbKzQo

The same happens if I run the HTML and CSS from a directory in my PC, so I think it has something to do with Django.

What could it be?

I've tried also this other answer:

python manage.py collectstatic --noinput --clear

from here (without results):

Django won't refresh staticfiles

base.html:

{% load staticfiles %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="{% block metadescription %}{% endblock %}">
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
    <link rel="stylesheet" href="{% static 'css/custom.css' %}">
    <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
    {#    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css"#}
    {#          integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">#}
    <title>Title</title>
</head>
<body>
<div>

    <div class="container">

    {% include 'navbar.html' %}
        <div class="container-fluid nav-bar-fixed-top my_top_navbar_div">


            {% block content %}
            {% endblock %}
        </div>
    </div>
    {% include 'footer.html' %}
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="{% static 'js/jquery-3.2.1.slim.min.js' %}"></script>
    <script src="{% static 'js/popper.min.js' %}"></script>
    <script src="{% static 'js/bootstrap.min.js' %}"></script>



</body>
</html>

navbar.html:

<!--- GALLITO NAVBAR --->

<nav class="navbar navbar-expand-md fixed-top navbar-bg">
    <a class="navbar-brand" href="#">Navbar</a>

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault"
            aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarsExampleDefault">


        <ul id="mi_menu" class="navbar-nav mr-auto my_custom_menu">

            <li class="nav-item active">
                <a class="nav-link" href="#">Stickers <span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item active">
                <a class="nav-link" href="#">Etiquetas</a>
            </li>
            <li class="nav-item active">
                <a class="nav-link" href="#">Magnetos</a>
            </li>
            <li class="nav-item active">
                <a class="nav-link" href="#">Pines</a>
            </li>
            <li class="nav-item active">
                <a class="nav-link" href="#">Pines</a>
            </li>
            <li class="nav-item active">
                <a class="nav-link" href="#">Empaques</a>
            </li>
        </ul>


        <ul class="navbar-nav ml-auto">
            <li class="nav-item">
                <a class="nav-link"><i class="fas fa-shopping-cart"></i></a>
            </li>

            {% if user.is_authenticated %}
                <li class="nav-item active">
{#                    <a class="nav-link" href="{% url 'logout' %}">Logout</a>#}
                </li>
                <li class="nav-item active">
                    <a class="nav-link" href="#">{{ user }}</a>
                </li>
            {% else %}
                <li class="nav-item active">
{#                    <a class="nav-link" href={% url 'login' %}>LogIn</a>#}
                </li>
            {% endif %}

            <li class="nav-item active">
                <a class="nav-link" href="#">Registro</a>
            </li>
        </ul>


    </div>
</nav>

custom.css:

body {
    font-family: 'Roboto', sans-serif;
}

/* === NavBar === */
.nav-item {
    letter-spacing: .2em;
    font-size: 14px;
    text-transform: uppercase;
}


.dropdown-item {

}


/* == Footer ==== */

.my_footer {
    background-color: #5a6268;
}

.my_footer p {
    padding-top: 20px;
    font-size: 14px;
}


/* == Category Page == */

.my_row_class {
    padding-top: 15px;
}

.my_row_class .mx-auto p {

    color: #000;
    font-size: 12px;
}


.my_row_class .mx-auto p a {

    color: #000;
    font-size: 12px;
    text-decoration: none;
}

.my_image {
    width: 100%;
    height: auto;
}

.my_title {
    font-size: 16px;
    text-transform: uppercase;
    letter-spacing: .2em;
}

.my_image_padding {
    padding-top: 16px;
}

.my_bottom_margin {
    margin-bottom: 10px;
}

.card-body h4 {
    font-size: 14px;
    text-transform: uppercase;
    letter-spacing: .2em;
}

/*=== Product Page ==*/

.my_prod_row_class {
    padding-top: 15px;
    padding-bottom: 20px;
}

.my_prod_row_class .mx-auto p {
    color: #000;
    font-size: 12px;
}


.my_prod_row_class .mx-auto p a {
    color: #000;
    font-size: 12px;
    text-decoration: none;
}


.my_prod_title {
    font-size: 16px;
    text-transform: uppercase;
    letter-spacing: .2em;
    padding-top: 15px;
    padding-bottom: 10px;
}

.my_prod_text {
    padding-right: 20px;
}

.my_search_text {
    padding-top: 20px;
}

/*== Cart ==*/


.my_custom_table {
    min-width: 400px;
    font-size: 14px;
}

.my_custom_thead {

    font-weight: normal;
    text-transform: uppercase;
    letter-spacing: .2em;
    background-color: #f8f9fa !important;

}

.custom_image {
    width: 100px;
    height: 100px;
}

.custom_a {
    text-decoration: none;
}

.custom_icon {
    text-decoration: none;
    color: gray;
}

.my_custom_button {

    margin-top: 5px;
}

.navbar-bg {
    background-color: black;
}

UPDATE 1:

I see that my new css class: .navbar-bg is not beeing loaded. Why is that? and How can I solve it? (CTRL + F5 doesn't solve this).

Also, this happens in Chrome and in Firefox (I'm using Ubuntu).

UPDATE 2:(settings.py)

"""
Django settings for perfectcushion project.

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

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/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/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^_67&#r+(c+%pu&n+a%&dmxql^i^_$0f69)mnhf@)zq-rbxe9z'

# 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',
    'shop',
    'search_app',
    'cart',
    'stripe',
    'order',
    'crispy_forms',

]

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

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates'),
                 os.path.join(BASE_DIR, 'shop', 'templates/'),
                 os.path.join(BASE_DIR, 'search_app', 'templates/'),
                 os.path.join(BASE_DIR, 'cart', 'templates/'),
                 os.path.join(BASE_DIR, 'order', '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',
                'shop.context_processor.menu_links',
                'cart.context_processor.counter'
            ],
        },
    },
]

WSGI_APPLICATION = 'perfectcushion.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/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/2.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/2.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/2.1/howto/static-files/

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media')


### Stripe Settings ###


STRIPE_PUBLISHABLE_KEY = 'pk_test_N0ksyIuO5d1ulLDuoMlLiU26'

STRIPE_SECRET_KEY = 'sk_test_fFHncrzOzBPS3XxDQM0TWMfy'

CRISPY_TEMPLATE_PACK = 'bootstrap4'

UPDATE 3:

Creating static_dirs inside static folder and then changing this:

# STATICFILES_DIRS = (
#     os.path.join(BASE_DIR, 'static'),
# )

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static', 'static_dirs'),
    )

and then doing collecstatic doesn't make effect:

manage.py@perfectcushion > collectstatic
bash -cl "/home/ogonzales/Escritorio/projects_envs/perfectcushion_env/bin/python /home/ogonzales/Escritorio/pycharm/helpers/pycharm/django_manage.py collectstatic /home/ogonzales/Escritorio/web_proyects/perfectcushion"
Tracking file by folder pattern:  migrations

You have requested to collect static files at the destination
location as specified in your settings:

    /home/ogonzales/Escritorio/web_proyects/perfectcushion/staticfiles

This will overwrite existing files!
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel:  yes

0 static files copied to '/home/ogonzales/Escritorio/web_proyects/perfectcushion/staticfiles', 119 unmodified.

Process finished with exit code 0

UPDATE 4: Project Structure:

解决方案

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

STATIC_ROOT is supposed to be destination folder for collectstatic command. That's where files will be copied from source directories.

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

STATICFILES_DIRS is the list of source folders for collectstatic. Additional folders. Because all the subfolders named static from any app listed in INSTALLED_APPS will be searched automatically by default. Which means - even thirdparty apps, e.g. DRF or whatever.

Again, in STATICFILES_DIRS you should list any source folders with staticfiles which are not /static/ subfolders of your django project apps. E.g. if you have somewhere /home/me/my_super_imgs/ and config:

STATIC_ROOT = '/var/opt/prod/static/'
STATICFILES_DIRS = (
    '/home/me/my_super_imgs/',
)

you will have all the files and subfolders of my_super_imgs inside /var/opt/prod/static/ after executing collectstatic. As well as all any content from /static/ subfolder of all the apps listed in INSTALLED_APPS.

If you have shop/static/ folder - its contents will be "collected" into staticfiles by default.

Note, you are trying to load static files under /static/ url in your template, but your destination folder is named as staticfiles. It's okay because you have configured both STATIC_ROOT and STATIC_URL, but may confuse because you have /static/ folder as well.

One more thing:

'DIRS': [os.path.join(BASE_DIR, 'templates'),
             os.path.join(BASE_DIR, 'shop', 'templates/'),
             os.path.join(BASE_DIR, 'search_app', 'templates/'),
             os.path.join(BASE_DIR, 'cart', 'templates/'),
             os.path.join(BASE_DIR, 'order', 'templates/'),]
    ,
    'APP_DIRS': True,

stop listing your app dirs here - APP_DIRS is enabled and this is enough.

upd

Why browser does not reflect css file changes?

There are many levels of caching between file on server's disk and rendered page on client-side. By doing this trick href="{% static 'css/custom.css' %}?20181209"> (see question symbol?) as I mentioned in comment under your question, you are changing full URL and it forces reloading of css (or any other) file, whilst physical file name is not changed. Update date after ? when file changed. This is a well known trick. This value may be date or hash of this file.

Also, you may introduce template tag like {% my_css %} which would insert static file names with defined date/hash/build parameter in the URL - to avoid copying this magic parameter into many templates.

Right now you may test reloading css file with parameter manually:

  • update css file
  • check that browser does not see changes by opening css file url
  • open the same url with any ?parameter
  • done, file content refreshed

这篇关于Django:无法更新CSS更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆