Css не изменяется django

Django: cannot update css changes

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 (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).

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):

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

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).

enter image description here

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' 

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:

[email protected] > 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:

Читайте также:  Catching java lang runtimeexception

enter image description here

Solution

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.

'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.

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=»?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.

Читайте также:  Php cli get args

Also, you may introduce template tag like 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

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Источник

Почему не обновляются стили css в django

а при изменении значения margin-top:100px; в файле style.css нечего не меняется хотя в браузере если меняю все работает.
И когда запускаю через http://127.0.0.1:8080 а не http://127.0.0.1:8000 то все работает

JavaScript — innerHTML и CSS — Не обновляются стили после вставки текста
Приветствую! Если что-то делаю неправильно, пожалуйста поправьте меня. Заранее спасибо за ответы.

Почему сайт не видите стили css
Поместил стили в папку resources/css указал путь как /css/style.css А на сайте отображаются только.

Почему после перенос сайта пропадают CSS стили?
Привет. Почему после миграции сайта на WP с хоста на локалку могут пропадать все css стили у всех.

ЦитатаСообщение от _ZombiE_ Посмотреть сообщение

Почему не все стили CSS работают в QPlainTextEdit при добавлении текста с тегами через appendHtml? PySide6
Когда добавляю новый текст в QPlainTextEdit через appendHtml с HTML и стилями, то в итоге не все.

Стили и скрипты не обновляются после изменения при просмотре в браузере
Сайт на джумле. Подключаю стили: <link rel="stylesheet" href="путь/custom.css" type="text/css"/>.

Django не загружает стили в шаблон
Django не хочет загружать стили css . Картинки и .js файлы загружаются без проблем . Windows 7.

Заставить работать стили в админпанели django 19 на windows 7
Всем привет. Топикстартер извини что здесь, но у меня почти такая же проблема. Установил django.

Почему данные в БД не обновляются?
Почему не идёт обновляется. Что я тут упустил Подскажите <? include ("block/bd.php"); .

Источник

Не применяются стили в Django. Что не так?

Основной документ находится в первом приложении — «index», а news.html находится в приложении — «news».

В первом приложении есть ещё документы в них стили работают.
А в основном надо вывести запись с папки models.py, с этим проблем нет, только стили не применяются!

from django.urls import path from . import views urlpatterns = [ path('', views.news, name='news'), ]
from django.shortcuts import render from .models import MyModel def news(request): news = MyModel.objects.all() return render(request, 'news/news.html', )
from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('index.urls')), path('news/', include('news.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

P.S. Не знаю надо ли это, но запишу
index/urls.py(первое приложение, где находятся основной HTML-документ и стили)

from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('about/', views.about, name='about'), path('contacts/', views.contacts, name='contacts') ]
from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request, 'index/index.html') def about(request): return render(request, 'index/about.html') def contacts(request): return render(request, 'index/contacts.html')

P.S.S. Стили пытался подключать не только с первого приложения(index), но и со второго(news), где находится news.html

Читайте также:  Древовидная структура в html

Простой 1 комментарий

Источник

Python-сообщество

[RSS Feed]

  • Начало
  • » Web
  • » CSS отказывается работать в Django.

#1 Авг. 25, 2018 13:59:46

CSS отказывается работать в Django.

Добрый день. Не работают стили CSS в шаблоне Html django. Не знаю, что да как.
index.html

 link rel="stylesheet" type="text/css" href="" /> div id="a"> p>Это текстp> div> 
STATIC_URL = '/static/' STATIC_PATH = os.path.join(BASE_DIR,'static') 

Разъясните пожалуйста чайнику, как работают настройки и напишите, что я должен дописать/убрать, чтобы оно работало как надо. Спасибо

#2 Авг. 26, 2018 02:50:40

CSS отказывается работать в Django.

В принципе все правильно, надо только проверить чтобы директория subs была в static а static в корне проекта.
А в settings.py есть строка STATICFILES_DIRS = ( os.path.join(BASE_DIR, “static”), ) .
Если все на месте должно работать. Сам пользуюсь этим вариантом.

#3 Авг. 26, 2018 12:17:35

CSS отказывается работать в Django.

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

Попробовал, не помогает. Путь до папок сделал картинкой. Где я накосячил так, что оно не хочет работать? При чем если менять id на другой, то цвет меняется, а если менять CSS стиль айди “а”, то меняй не меняй, цвет не хочет меняться

Отредактировано MEOW (Авг. 26, 2018 12:20:20)

attachment

Прикреплённый файлы:
1.PNG (4,0 KБ)

#4 Авг. 26, 2018 21:35:36

CSS отказывается работать в Django.

Вы static директорию запихнули в приложение subs, subs это у вас же приложение, верно? static должна быть на одном уровне с manage.py, т.е. корень проекта. И вообще, по какому пособию изучаете? Эта тема везде неплохо раскрыта.

MEOW
При чем если менять id на другой, то цвет меняется, а если менять CSS стиль айди “а”, то меняй не меняй, цвет не хочет меняться

Это совсем другая история, это браузер кэширует css файлы, надо чистить кэш браузера или как вариант перезапускать сервер на другом порте.

Источник

Оцените статью