Django 1.8 static files doesnt work - css

Im using the 1.8 version of Django and my CSS, JS or images are not working, i really dont know why, my project folder is like
Project
Jetint
Static
CSS
My settings:
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',
'clients',
'front',
)
MIDDLEWARE_CLASSES = (
'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',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'jetint.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['jetint/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',
],
},
},
]
WSGI_APPLICATION = 'jetint.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'bd',
'USER': 'bd',
'PASSWORD': 'xxxx',
'HOST': '',
'PORT': '',
'ATOMIC_REQUESTS': True
}
}
TEMPLATE_DIRS = (BASE_DIR, 'jetint/templates')
# Internationalization
# https://docs.djangoproject.com/en/1.8/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.8/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = (
os.path.join(BASE_DIR, '/static/'),
)
STATICFILES_DIRS = (STATIC_ROOT,)
and my base.html
<!DOCTYPE html>
<html lang="en">
<head>
<title> - {% block title-section%}{% endblock %}</title>
<meta charset="utf-8">
<meta name = "format-detection" content = "telephone=no" />
{# <link rel="icon" href="{{ STATIC_URL }}images/favicon.ico"> #}
{# <link rel="shortcut icon" href="{{ STATIC_URL }}images/favicon.ico" /> #}
{% load staticfiles %}
<link rel="stylesheet" href="{{ STATIC_URL }}css/camera.css">
<link rel="stylesheet" href="{{ STATIC_URL }}css/stuck.css">
<link rel="stylesheet" href="{{ STATIC_URL }}css/style.css">
but nothing works, css, js files, or images. please help?
EDIT:
now my html looks like this:
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<title> Jet Internacional - {% block title-section%}{% endblock %}</title>
<meta charset="utf-8">
<meta name = "format-detection" content = "telephone=no" />
{# <link rel="icon" href="{{ STATIC_URL }}images/favicon.ico"> #}
{# <link rel="shortcut icon" href="{{ STATIC_URL }}images/favicon.ico" /> #}
<link rel="stylesheet" href="{% static 'css/camera.css' %">
<link rel="stylesheet" href="{% static 'css/stuck.css' %">
<link rel="stylesheet" href="{{ % static 'css/style.css'%">
<script src="{{ STATIC_URL }}js/jquery.js"></script>
<script src="{{ STATIC_URL }}js/jquery-migrate-1.1.1.js"></script>
<script src="{{ STATIC_URL }}js/script.js"></script>
<script src="{{ STATIC_URL }}js/superfish.js"></script>
<script src="{{ STATIC_URL }}js/jquery.equalheights.js"></script>
<script src="{{ STATIC_URL }}js/jquery.mobilemenu.js"></script>
<script src="{{ STATIC_URL }}js/jquery.easing.1.3.js"></script>
<script src="{{ STATIC_URL }}js/tmStickUp.js"></script>
<script src="{{ STATIC_URL }}js/jquery.ui.totop.js"></script>
<script src="{{ STATIC_URL }}js/camera.js"></script>
<!--[if (gt IE 9)|!(IE)]><!-->
<script src="{{ STATIC_URL }}js/jquery.mobile.customized.min.js"></script>
<!--<![endif]-->
<script src="{{ STATIC_URL }}js/jquery-ui-1.10.3.custom.js"></script>
<script>
$(document).ready(function(){
jQuery('#camera_wrap').camera({
loader: false,
pagination: false ,
minHeight: '200',
thumbnails: false,
height: '25.625%',
caption: false,
navigation: true,
fx: 'mosaic'
});
$().UItoTop({ easingType: 'easeOutQuart' });
$('#stuck_container').tmStickUp({});
});
$(function() {
jQuery( "#accordion" ).accordion({
collapsible: true,
heightStyle: "content",
});
});
</script>
<!--[if lt IE 8]>
{% comment %}<div style=' clear: both; text-align:center; position: relative;'>
<a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode">
<img src="http://storage.ie6countdown.com/assets/100/images/banners/warning_bar_0000_us.jpg" border="0" height="42" width="820" alt="You are using an outdated browser. For a faster, safer browsing experience, upgrade for free today." />
</a>
</div>{% endcomment %}
<![endif]-->
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<link rel="stylesheet" media="screen" href="css/ie.css">
<![endif]-->
</head>
<body class="page1" id="top">
<!--==============================
header
=================================-->
<header>
<!--==============================
Stuck menu
=================================-->
<section id="stuck_container">
<div class="container">
<div class="row">
<div class="grid_12">
<h1>
<a href="/">
<img src="{% static 'images/logo-rif.png' %}" width="200px;" alt="Logo alt">
</a>
</h1>
<div class="header_socials">
{# Registro #}
</div>
and my settings...
import os
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.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'm9y8koy5%cm4#_=sk_hjlbl$z%mgj*8dztu13#)^zr(j*g#q0m'
# 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',
'clients',
'front',
)
MIDDLEWARE_CLASSES = (
'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',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'jetint.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['jetint/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',
],
},
},
]
WSGI_APPLICATION = 'jetint.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'bd',
'USER': 'bd',
'PASSWORD': '...',
'HOST': '',
'PORT': '',
'ATOMIC_REQUESTS': True
}
}
TEMPLATE_DIRS = (BASE_DIR, 'jetint/templates')
# Internationalization
# https://docs.djangoproject.com/en/1.8/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.8/howto/static-files/
STATIC_URL = 'jetint/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), 'static'),
)

Put {% load staticfiles %} at the very top of the html document.
Also try:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), 'static'),
)
- - - Edit:
Additionally, to call static files in html templates, follow this format:
<link href="{% static 'css/camera.css' %}" rel="stylesheet" media="screen">

I had the same problem, but solved it.
I put this in my settings.py:
STATICFILES_FINDERS = (
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
)
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
Then I rebooted the test server.

Put {% load staticfiles %} at the very top of the html document.
Call static file like this :
<link href="{% static 'css/camera.css' %}" rel="stylesheet" media="screen">
In settings try with using any one of STATIC_ROOT or STATICFILES_DIRS.
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')
or
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), 'static'),
)

if BASE_DIR = /home/myUser/Project is your BASE DIR then, just like you added 'jetint' for your template url, you could try adding it to your static like
STATIC_URL = 'jetint/static/'
Or, better yet, make your BASE DIR = /home/myUser/Project/jetint

from django.conf import settings
STATIC_URL = settings.STATIC_URL
def index(request):
return render(request, '*.html', {'STATIC_URL':STATIC_URL})
'''
A bad way
'''

Just add this in your settings.py with 'static' folder in the same place with manage.py
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'))

Related

How put css on django?

I have a big problem.Django doesn't recognize my css files. PHG
My css file is located in polls, but Django won't recognize it as a static file
My home.html
<link rel="stylesheet" type="text/css" href="home.css">
<title>121212</title>
<body>
<div id="1212">
<li class="fafa">12112</li>
</div>
</body>
my settings.py
STATIC_URL = '/static/'
STATIC_DIRS = [os.path.join(BASE_DIR, "static"),]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')```
It is a very SMALL problem, Mr XD.
In your template: {% load static %}
And then: <link href="{% static 'home.css' %}" rel="stylesheet">

static files can't be uplaod on cpanel

I get error that my static files can't be full executed in my wep app
This app works correctily on my pc but not on c panel
I am on sharehost so I can't use nginex
How solve this problem
This is my setting:
import os
from pytz import common_timezones
# 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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'r&94#o%)q8s-=gmxw#8a9o5161%90&2jo$0*&a&57*5$rx)#ar'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = ["*"]
# Application definition
INSTALLED_APPS = [
#default
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#local components
'omuser',
'ommessage',
'omformflow',
'omflow',
'omdashboard',
'omformmodel',
'omservice',
'ommission',
]
AUTH_USER_MODEL = 'omuser.OmUser'
LOGIN_REDIRECT_URL = '/home/'
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'omflow.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',
'django.template.context_processors.i18n',
'django.template.context_processors.static',
'django.template.context_processors.media',
],
},
},
]
WSGI_APPLICATION = 'omflow.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
# Password validation
# https://docs.djangoproject.com/en/2.2/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.2/topics/i18n/
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
LANGUAGES = [
("en", "English"),("zh-hant", "Traditional_Chinese"),("zh-hans", "Simplified_Chinese"),("ja", "Japanese"),("ar","Arabic")
]
LANGUAGE_CODE = 'en'
#TIME_ZONE = 'Africa/Cairo'
TIME_ZONES = [(tz, tz) for tz in common_timezones]
DATE_FORMAT = '%Y-%m-%d'
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
DATETIME_INPUT_FORMATS = '%Y-%m-%d %H:%M:%S'
USE_I18N = True
USE_L10N = False
# USE_TZ = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
# SESSION_COOKIE_AGE = 3600
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
FILE_UPLOAD_TEMP_DIR = BASE_DIR
FILE_UPLOAD_MAX_MEMORY_SIZE = 52428800
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATIC_URL = '/static/'
# static url Mapping folder
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'staticfiles'),
#os.path.join(BASE_DIR, 'omuser', 'staticfiles'),
)
# staticfiles_dirs Mapping folder
#STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_ROOT = os.path.join(BASE_DIR, '..', 'static')
LOG_DIR = os.path.join(BASE_DIR, 'logs')
LOG_LEVEL = 'ERROR'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'simple': {
'format': '[%(asctime)s] - %(levelname)-8s - %(message)s',
'datefmt': DATETIME_FORMAT,
},
},
"filters": {
"infofilter": {
"()": "omflow.syscom.default_logger.LowLevelFilter",
"level": 20
},
"warnfilter": {
"()": "omflow.syscom.default_logger.HighLevelFilter",
"level": 30
}
},
'handlers': {
'consoleInfo': {
'class': 'logging.StreamHandler',
'formatter': 'simple',
"filters": ["infofilter"]
},
'consoleError': {
'class': 'logging.StreamHandler',
'formatter': 'simple',
"stream": "ext://sys.stdout",
"filters": ["warnfilter"]
},
'omlogfile': {
'class': 'logging.handlers.TimedRotatingFileHandler',
'filename': os.path.join(LOG_DIR, 'omflow.log'),
'encoding':'utf-8',
'formatter': 'simple',
'when': 'midnight',
'backupCount': 10,
'delay': True
},
'djangolog': {
'class': 'logging.handlers.TimedRotatingFileHandler',
'filename': os.path.join(LOG_DIR, 'djangolog.log'),
'encoding':'utf-8',
'formatter': 'simple',
'when': 'midnight',
'backupCount': 10,
'delay': True
},
},
'loggers': {
'django': {
'handlers': ['consoleInfo','consoleError','djangolog'],
'level': LOG_LEVEL,
'propagate': False
},
'omflowlog': {
'handlers': ['omlogfile'],
'level': LOG_LEVEL,
'propagate': False
},
},
}
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3","NAME": os.path.join(BASE_DIR, "db.omflow"),"OPTIONS": {"timeout": 300,}}}
This is my template:
<!DOCTYPE html>
{% load static %}
{% load i18n %}
{% load omflow_tags %}
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
{% include 'base_import.html' %}
<!-- AdminLTE Skins. We have chosen the skin-blue for this starter
page. However, you can choose any other skin. Make sure you
apply the skin class to the body tag so the changes take effect. -->
<link rel="stylesheet" href="{% static 'css/skins/skin-syscom.css' %}">
<!-- AdminLTE App -->
<script src="{% static 'js/adminlte.min.js' %}"></script>
</head>
<!--
BODY TAG OPTIONS:
=================
Apply one or more of the following classes to get the
desired effect
|---------------------------------------------------------|
| SKINS | skin-blue |
| | skin-black |
| | skin-purple |
| | skin-yellow |
| | skin-red |
| | skin-green |
|---------------------------------------------------------|
|LAYOUT OPTIONS | fixed |
| | layout-boxed |
| | layout-top-nav |
| | sidebar-collapse |
| | sidebar-mini |
|---------------------------------------------------------|
-->
<body class="hold-transition skin-syscom sidebar-mini">
<div class="wrapper">
<!-- Main Header -->
<header class="main-header">
{% include 'base_header.html' %}
</header>
<!-- Left side column. contains the logo and sidebar -->
<aside class="main-sidebar">
{% include 'base_l_aside.html' %}
</aside>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
{% block content %}
{% endblock %}
</div>
<!-- /.content-wrapper -->
<!-- Main Footer -->
<footer class="main-footer">
<!-- To the right -->
<div class="pull-right hidden-xs">
{% omflow_version %} {% omflow_version_type %}
</div>
<!-- Default to the left -->
<strong>© 2020 The SYSCOM Group.</strong> {% trans '版權所有.'%}
</footer>
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar -->
<div class="control-sidebar-bg"></div>
</div>
<!-- ./wrapper -->
{% include 'base_component.html' %}
</body>
</html>
And this is suptemplate
{% load static %}
{% load i18n %}
{% load omflow_tags %}
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>OMFLOW</title>
<!-- Tell the browser to be responsive to screen width -->
<link rel="shortcut icon" href="{% static "img/favicon.ico" %}" />
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link rel="stylesheet" href="{% static 'components/bootstrap/dist/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'plugins/fontawesome-free-5.13.0-web/css/all.css' %}">
<link rel="stylesheet" href="{% static 'plugins/fontawesome-free-5.13.0-web/css/v4-shims.css' %}">
<link rel="stylesheet" href="{% static 'components/bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css'%}">
<link rel="stylesheet" href="{% static 'plugins/timepicker/bootstrap-timepicker.min.css'%}">
<link rel="stylesheet" href="{% static 'components/bootstrap-datetimepicker-master/css/bootstrap-datetimepicker.min.css'%}">
<!-- DataTables -->
<link rel="stylesheet" href="{% static 'components/datatables.net-bs/css/dataTables.bootstrap.min.css'%} ">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<link rel="stylesheet" href="{% static 'plugins/iCheck/minimal/blue.css' %}">
<!-- Google Font
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic"> -->
<link rel="stylesheet" href="{% static 'css/jquery-simple-tree-table.css' %}">
<!-- Select2 -->
<link rel="stylesheet" href="{% static 'components/select2/dist/css/select2.css' %}">
<!-- Ion Slider -->
<link rel="stylesheet" href="{% static 'plugins/Ion-Slider/ion.rangeSlider.min.css' %}">
<!-- daterange picker -->
<link rel="stylesheet" href="{% static 'components/bootstrap-daterangepicker/daterangepicker.css' %}">
<link rel="stylesheet" href="{% static 'plugins/CodeMirror/lib/codemirror.css' %}">
<link rel="stylesheet" href="{% static 'plugins/CodeMirror/theme/eclipse.css' %}">
<link rel="stylesheet" href="{% static 'plugins/SweetAlert2/dist/sweetalert2.css'%}">
<link rel="stylesheet" href="{% static 'plugins/select2-to-tree-master/src/select2totree.css' %}">
<link rel="stylesheet" href="{% static 'css/AdminLTE.min.css' %}">
<link rel="stylesheet" href="{% static 'css/omflow.css'%}?version={%omflow_version%}">
<script type="text/javascript" src="{% url 'javascript-catalog' %}"></script>
<!-- jQuery 3 -->
<script src="{% static 'components/jquery/dist/jquery.min.js'%}"></script>
<!-- jQuery UI -->
datetimepicker.min.js'%}"></script>
<script src="{% static 'components/bootstrap-datetimepicker-master/js/locales/bootstrap-datetimepicker.zh-hant.js'%}"></script>
<script src="{% static 'components/bootstrap-datetimepicker-master/js/locales/bootstrap-datetimepicker.zh-hans.js'%}"></script>
<script src="{% static 'components/bootstrap-datetimepicker-master/js/locales/bootstrap-datetimepicker.ja.js'%}"></script>
<!-- DataTables -->
<script src="{% static 'components/datatables.net/js/jquery.dataTables.min.js' %}"></script>
<script src="{% static 'components/datatables.net-bs/js/dataTables.bootstrap.min.js' %}"></script>
<script src="{% static 'js/jquery-simple-tree-table.js' %}"></script>
<!-- Select2 -->
you can find the answer here
404 Static file not found - Django
so add to your urle following
from django.conf.urls.static import static
from .settings import STATIC_URL,STATIC_ROOT
urlpatterns += static(STATIC_URL, document_root=STATIC_ROOT)

Django CSS File Not Working/Not being served

I cannot figure out why my css file is not working. I added my css, html and settings.py files. Can anyone help? I've tried collectstatic but get an error:
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'D:\\mysite\\dreamboard\\static\\dreamboard\\style.css'
I tried replacing my path in the STATICFILES_DIRS but it still does not work. I'm not sure what to do. It could be the bootstrap? Or something. I want to have a style sheet so I can my form to a popup button. Everything is titled and spelled correctly. Any ideas?
Here are my files:
{% load static %}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% load crispy_forms_tags %}
<link rel="stylesheet" type="text/css" href="{% static 'dreamboard/style.css' %}">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/73cead4581.js" crossorigin="anonymous"></script>
<title>Hello, world!</title>
</head>
<body class="bg-light">
<h1>Hello, world!</h1>
<div class="container">
<div class="row bg-dark">
<div class=" col-sm">
<h1 style="color:white">Dreamboard</h1>
</div>
<div class="col-sm">
<button class="btn-lg btn-primary" type="submit">Add Dream</button>
</div>
</div>
</div>
</div>
<form class="" action="" method="post" autocomplete="off">
{% csrf_token %}
<div class="row">
<div class="col-md-6">
{{form.first_name|as_crispy_field}}
</div>
<div class="col-md-6">
{{form.last_name|as_crispy_field}}
</div>
</div>
{{form.dreamItem|as_crispy_field}}
<br>
<button type="submit" class="d-grid gap-2 col-12 btn btn-success">Submit</button>
</form>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.5.4/dist/umd/popper.min.js" integrity="sha384-q2kxQ16AaE6UbzuKqyBE9/u/KzioAlnx2maXQHiDX9d4/zp8Ok3f+M7DPm+Ib6IU" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.min.js" integrity="sha384-pQQkAEnwaBkjpqZ8RU1fF1AKtTcHJwFl3pblpTlHXybJjHpMYo79HY3hIi4NKxyj" crossorigin="anonymous"></script>
-->
</body>
</html>
css
.body {
background-color: blue;
}
.title {
color: blue;
}
settings.py
from pathlib import Path
# 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 = 'wpx1d9%a4(9-c%+$=or6ez+9*d7&)lo!d5(8cu3##3votm)!72'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'dreamboard',
'crispy_forms',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
CRISPY_TEMPLATE_PACK = 'bootstrap4'
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 = '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/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'dreams',
'USER': 'postgres',
'PASSWORD': 'password',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
# 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_URL = '/static/'
STATICFILES_DIRS = [
"/mysite/dreamboard/static/dreamboard/style.css",
]
I am not sure because I don't think many people use an absolute path to connect to static files. Try creating a new folder named "static", In the same folder where you have the manage.py file. and add this into your settings.py.
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_DIR = os.path.join(BASE_DIR,"static")
check the settings.py code here
Add the below code directing django to the static file location
# Static files (CSS, JavaScript, Images) #https://docs.djangoproject.com/en/3.1/howto/static-files/
> STATIC_URL = '/static/'
> STATICFILES_DIRS = [
> STATIC_DIR,
> ]
Now link it in the HTML using ,
<link rel="stylesheet" href="{% static 'css/base.css' %}">
(create a folder called css inside the static folder in your base directory)
You have named your class "bg-light", but in your css code it looks like you are trying to target a class in your css file named "body" when you don't have a class name body. If you are tying to access the body tag which it looks like your trying to do then you have to get rid of the "." you have in your ".body{}". You have also done the same thing for your title tag which is ".title". Your not targeting what you think your trying to target.
#Your HTML Code
<body class="bg-light">
#Your css code >>> pay close attention to the "."
.body {
background-color: blue;
}
Try This:
body{
background-color: blue;
}
title{
background-color:blue;
}

Django: can't load CSS files that are in /static

Since I finished the backend of my Django website I started adding some style.
My html files are displayed but it seems no css has been linked to them however the path is correct when I show the source code in Firefox.
mywebsite/
----blog/
----mywebsite/
----static/
--------css/
------------struct.css
----templates/
--------layouts/
--------errors/
------------404.html
--------html/
------------struct.html
Django version: 2.1.7
settings.py:
DEBUG = False
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
# other apps...
'django.contrib.staticfiles',
]
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
struct.html:
{% load static %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width; initial-scale=1.0;">
<link rel="stylesheet" href="{% static 'css/struct.css' %}">
<title>test</title>
</head>
<body>
<p>test</p>
</body>
</html>
struct.css:
p{
color:red:
}
body{
background-color:black:
}
Generally static files path should be like this appname/static/appname/yourfiles
there is no need to change url patterns.
Assuming your appname is Myapp , the proper path for your css file is
Myapp/static/Myapp/css/struct.css
For including static files , add below line in settings.py
STATIC_URL = '/static/'
and in your html template
<!doctype html>
{% load static %}
<link rel="stylesheet" href="{% static 'Myapp/css/struct.css' %}">
If you are having your static files within the app then there is no need to use
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
You can refer Managing Static Files in django documentation .
define static root in settings.py
STATIC_ROOT = BASE_DIR + '/static/'
hope it helps
refer this
if you are running this application on localhost then you may try to set DEBUG = True
if you mistakenly set it to False,
Because it was fixed for me that way.

Static files not loading in django 1.6

My structure looks something like this:
myproject/
app1/
static/
css/
style.css
myproject/
settings.py
static/
css/
style.css
db.sqlite3
in settings.py I have:
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..'))
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
# blank
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
in my index.html I have:
<link rel="stylesheet" type="text/css" href="/static/css/style.css" />
I am trying to load css from myproject/static folder but whenever I load index.html it's looking into /app1/static/css/style.css, db.sqlite3 is working though.
I even tried removing app/static folder, it did not work. What am I doing wrong?
add {% load staticfiles %} at the top of your template
<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}" />
In settings.py,
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
No need of STATIC_ROOT, if you're running on localhost.
You forgot to add the Static tags to load your files in the templates:
At the beginning of your html file you have to put
{% load staticfiles %}
then add the static tag in your path
<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %} />
see the documentation in django:
https://docs.djangoproject.com/en/1.6/howto/static-files/
kudo to the one who just answered you got it faster ;)

Resources