首页 文章

Django:无法更新css更改

提问于
浏览
0

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

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

但是,如果我在CodePen这样的网站中粘贴相同的 HTMLCSS 代码就可以了(我的导航栏获得黑色背景) .

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

如果我从我的PC中的目录运行HTML和CSS,也会发生同样的情况,所以我认为它与Django有关 .

What could it be?

我也试过了另一个答案:

python manage.py collectstatic --noinput --clear

从这里(没有结果):

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:

我看到我的新css类: .navbar-bg 没有加载 . 这是为什么?我该如何解决? (CTRL F5没有解决这个问题) .

此外,这发生在Chrome和Firefox中(我使用的是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

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/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: 项目结构:

3 回答

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

    STATIC_ROOT 应该是 destination 命令的 destination 文件夹 . 这是从源目录复制文件的地方 .

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

    STATICFILES_DIRScollectstatic 的_5221_文件夹的list . 其他文件夹 . 因为默认情况下将搜索 INSTALLED_APPS 中列出的任何应用程序中名为 static 的所有子文件夹automatically . 这意味着 - 即使是第三方应用,例如DRF或其他什么 .

    同样,在 STATICFILES_DIRS 中,您应该列出任何带有静态文件的源文件夹 are not /static/ subfolders of your django project apps . 例如 . 如果你有某个地方 /home/me/my_super_imgs/ 和配置:

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

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

    如果您有 shop/static/ 文件夹 - 默认情况下其内容将"collected"成 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': True,
    

    停止列出您的 app dirs - APP_DIRS 已启用,这就足够了 .

    更新

    为什么浏览器不能反映css文件的变化?

    服务器磁盘上的文件与客户端上呈现的页面之间存在多种级别的缓存 . 通过我在你的问题评论中提到的这个技巧 href="{% static 'css/custom.css' %}?20181209"> (参见问题符号?),你正在改变完整的URL并强制重新加载css(或任何其他)文件,而物理文件名不会改变 . 文件更改后 ? 之后更新日期 . 这是一个众所周知的技巧 . 此值可以是此文件的日期或哈希值 .

    此外,您可以引入模板标记,如 {% my_css %} ,它将在URL中插入具有已定义的日期/哈希/构建参数的静态文件名 - 以避免将此魔术参数复制到许多模板中 .

    现在您可以手动测试使用参数重新加载css文件:

    • 更新css文件

    • 通过打开css文件网址检查浏览器是否看不到更改

    • 用任何 ?parameter 打开相同的网址

    • 完成,文件内容刷新

  • 1

    所以,我发现如果:

    1)更改 staticfiles/css 中的 custom.css 文件,然后运行: collecstatic 不会更新 static/css 文件夹中的custmo.css .

    这就是为什么我的更新没有反映在不同的浏览器上 .

    2)即使我在 static/css 中删除 custom.css 然后运行 collecstatic 来创建/更新 custom.css ,它也不会发生 . 并且浏览器不反映我想要的css文件中的更改 .

    3)对我来说,解决方案是直接在 static/css 文件夹中进行修改,在这里确切地说: static/css/custom.css ,然后在浏览器中可以看到更改,在这种情况下,导航栏背景为黑色 .

    这是应该怎么做的?

  • 0

    您可以测试此方法 . 我希望对你有好处

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

    然后在static / static_dirs文件夹中添加静态文件 .

相关问题