index.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{% static 'style.css' %}">
<title>Document</title>
</head>
<body>
<h1 class="heading">This is the Heading</h1>
</body>
</html>
settings.py (my app name is base)
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'base'
]
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 = 'testpro.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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',
],
},
},
]
WSGI_APPLICATION = 'testpro.wsgi.application'
...
STATIC_URL = 'static/'
STATICFILES_DIRS = BASE_DIR, 'static'
Folder structure is like this:
project folder
/static
/style.css
CSS contains a simple color change and it is not working.
I've tried linking the css file in different ways and nothing seems to be working. I don't know how or why but sometimes it suddenly works and then suddenly stops working.
Instead of this:
STATIC_URL = 'static/'
STATICFILES_DIRS = BASE_DIR, 'static'
Try this:
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
You don't need to specify base directory in templates array.
DIRS': [BASE_DIR, 'templates'],
Just let it be empty.
DIRS': [],
and all other looks fine just make sure about CSS files. and it's location.
add this to the
<head>
<link href="{%static 'style.css'%}" rel="stylesheet">
</head>
and
add this to the testpro (urls.py)
from testpro import settings
urlpatterns = [
// here goes your urls
]
//at the bottom add this
urlpatterns += static(settings.STATIC_URL , document_root=settings.STATICFILES_DIRS)
and in the settings.py
change
STATICFILES_DIRS= BASE_DIR, 'static' to
STATIC_ROOT = os.path.join(BASE_DIR,'static')
Change this part of the settings.py to something like this:
STATIC_URL = 'static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, '<Your APP name goes here>\static'),)
If you have an 'css' subfolder inside your static folder then you need to add that to the relative path in your HTML template like this:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<title>Document</title>
</head>
<body>
<h1 class="heading">This is the Heading</h1>
</body>
</html>
I hope that helps you!
Related
I have tested to embedded css style into html template, but it doesn't load css files, my configure as below, could you please help assist ?
checkstatic\showstatic\templates\index.html
<!DOCTYPE html>
<meta charset="UTF-8">
<html lang="en">
<head>
{% load static%}
<link rel="stylesheet" type="text/css" href="{% static 'css/mystyle.css' %}">
</head>
<body>
<img src="{% static 'logo1.png' height="200" width="200" class="d-inline-block align-top" %}" alt="">
<h1 class="test">hahahaha</h1>
</body>
</html>
checkstatic\static\css\mystyle.css
.test{
color: red;
}
my settings:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'showstatic'
]
...
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'checkstatic/static/')
]
when i access the index site, it only apply h1 tag, it can not load red color as the css config.
Statics are used to get and use complete files (css, images, js, etc), in your image it should be:
<img src="{% static 'logo1.png' %}" height="200" width="200" class="d-inline-block align-top" alt="">
Leaving the properties of the img outside the static block.
first you should create directory=> static*
after then add base directory in setting:
STATICFILES_DIRS = [
BASE_DIR / 'directory_name'] // typically the name is: static_root
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR , 'media')
then: insert urls in main project
from django.conf import settings
from django.conf.urls.static import static
+static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)
!!attention !! ==> you should insert {%load static %} at above each of html pages
if you want to know more, follow https://docs.djangoproject.com/en/4.0/howto/static-files/
I'm using Sass for my Django(3.2.6) website with the help of libraries called django-compressor and django-sass-processor to compile it to a .css file. It works fine during development but when I try to disable the DEBUG mode in the settings the error will pop-up.
Refused to apply style from 'http://127.0.0.1:8000/static/styles.css'
because its MIME type ('text/html') is not a supported stylesheet MIME
type, and strict MIME checking is enabled.
Setting up the library I've added the following code to my settings.py (between ---- lines):
# Application definition
INSTALLED_APPS = [
--------------------------------------------------------------------
'sass_processor',
--------------------------------------------------------------------
'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 = 'openfiles.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [str(BASE_DIR.joinpath('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 = 'openfiles.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Manila'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
------------------------------------------------------------------------
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'static'
SASS_PROCESSOR_ROOT = STATIC_ROOT
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'sass_processor.finders.CssFinder',
]
-------------------------------------------------------------------------------
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Here are my static directory files structure BEFORE running library:
.
├── public (folder for images)
├── _scss (folder for .scss files)
└── styles.scss
AFTER running library, it created two files called styles.css.map and styles.css:
.
├── public
├── _scss
├── styles.css
├── styles.css.map
└── styles.scss
To access scss tags, HTML now use {% load scss_tags %} tag, here is my head.html:
{% load sass_tags %}
<head>
<meta charset="UTF-8">
<link href="http://gmpg.org/xfn/11" rel="profile">
<link type="text/plain" rel="author" href="{% url 'index' %}/humans.txt">
<!-- Enable responsiveness on mobile devices-->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
<meta property="og:title" content="{{ site_title }}">
<meta property="og:site_name" content="{{ site_brand_name }}">
<meta property="og:url" content="{% url 'index'} %">
<meta property="og:description" content="{{ site_description }}">
<meta property="og:type" content="website">
<meta property="og:image" content="{% sass_src 'public/meta-img.png' %}">
<link rel="stylesheet" href="https://unicons.iconscout.com/release/v2.0.1/css/unicons.css">
<title>
{% block title %}
Open Siena Files
{% endblock title %}
</title>
<!-- CSS -->
<link type="text/css" rel="stylesheet" href="{% sass_src 'styles.scss' %}" >
<!-- Icons -->
<link rel="shortcut icon" href="{% sass_src 'public/favicon.ico' %}">
</head>
But when running it without DEBUG mode the browser produces the error. YES YES YES. I already search for a solution but nothing seems to fit with specific problem I have about library converting scss to css.
I am new to Django and I am having a challenge in importing static files into my main HTML document. Can anybody help? Below is the approach I am following
My project structure looks like below. Hi2 is the project
settings.py looks like below. I did all the Important settings related to Static Files
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR = os.path.join(BASE_DIR,'static')
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp'
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFIELS_DIRS=[
STATIC_DIR,
]
My view file looks like below
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'myapp/index.html')
Finally imported CSS into my index.html in the below way. In the 3rd line Used {% load static %} and in 14th and 17th lines used "{% static "file location" %}". But it's not all reflecting when viewd Index.html page.
1) <!DOCTYPE html>
2) <html lang="en">
3) {% load static %}
4) <head>
5)
6) <meta charset="utf-8">
7) <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
8) <meta name="description" content="">
9) <meta name="author" content="">
10)
11) <title>Home</title>
12)
13) <!-- Bootstrap core CSS -->
14) <link href="{% static 'myapp/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
15)
16) <!-- Custom styles for this template -->
17) <link href="{% static 'myapp/css/simple-sidebar.css' %}" rel="stylesheet">
18)
19) </head>
Any help is highly appreciated
Thanks In Advance
Venk
I am trying to add a logo to my site, but for some reason it just isn't showing up.I have configured my code to the best of my knowledge but here is my code.
First i made sure django.contrib.staticfiles is included in my INSTALLED_APPS.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
]
i then ensured i defined STATIC_URL in my settings.py. I am only using one STATIC
STATIC_URL = '/static/'
STATICFILES_DIR = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
In my templates, i used the static template tag to build the URL for the relative path using the configured STATICFILES_STORAGE
{% 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, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
{% block title%}
{% endblock title%}
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="{%url 'index' %}">
<img src="{% static 'img/ATbrAaMRc.jpg' %}" alt='Image'>
</a>
Any help is appreciated.
There was a typo in the original post.
STATICFILES_DIR was used instead of STATICFILES_DIRS (Note the "S" at the end).
Fixing this allowed the "static" folder to be stored outside of the "blog" folder.
(Source: https://docs.djangoproject.com/en/3.0/howto/static-files/)
moving the static folder to the blog app worked.
I am able to load my static images, however; when it comes to loading my custom css sheets I cannot seem to get it working.
Because my static images are loading, I believe that my settings.py is set up properly, however, I could be wrong.
My static files for css and images are located within /static/img/hive.png and /static/css/main.css respectively.
Any help is greatly appreciated!
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
ALLOWED_HOSTS = []
DEBUG = True
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 = 'ideas.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 = 'ideas.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
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',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
home.html
{% 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, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<!-- personal css -->
<link rel="stylesheet" href="{% static "css/main.css" %}">
</head>
<body>
<img src="{% static "img/hive.png" %}" alt="My image"/>
<!-- jQuery first, then Tether, then Bootstrap JS. -->
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</body>
</html>
Had to run 'python manage.py collectstatic' for my static files to update.