I've followed this tutorial to make a sample project. The structure of the files is:
- mysite
- mysite
- __init__.py
- settings.py
- urls.py
- wsgi.py
- polls
- migrations
- templates
- polls.html
- static
- script.js
- style.css
- admin.py
- models.py
- tests.py
- urls.py
- views.py
- manage.py
Everything works well, but, the problem is using of Django-pipeline for managing the assets. I've configured my project as same as below codes, but it doesn't load assets properly.
settings.py
INSTALLED_APPS = (
.
.
'django.contrib.staticfiles',
'pipeline',
'polls',
)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_files')
PIPELINE_ENABLED = True
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
PIPELINE_CSS_COMPRESSOR = 'pipeline.compressors.cssmin.CSSMinCompressor'
PIPELINE_CSSMIN_BINARY = 'cssmin'
PIPELINE_JS_COMPRESSOR = 'pipeline.compressors.slimit.SlimItCompressor'
PIPELINE_CSS = {
'pollsX': {
'source_filenames': (
'style.css',
),
'output_filename': 'styles1.css',
'variant': 'datauri',
},
}
PIPELINE_JS = {
'pollsX': {
'source_filenames': (
'script.js',
),
'output_filename': 'scripts1.js',
}
}
polls.html
{% load compressed %}
{% compressed_css 'pollsX' %}
<div class='red-me'>
<h1> Hi! I'm a templ! </h1>
</div>
style.css
.red-me {
color: red;
}
The generated output for http://127.0.0.1/polls is
<link href="/static/styles1.css" rel="stylesheet" type="text/css" />
<div class='red-me'>
<h1> Hi! I'm a templ! </h1>
</div>
It can not load /static/styles1.css file in the browser. Even, I tested ./manage.py collectstatic without any success. Did I miss something?
Python-3.4 and Django-1.7
Django pipline updates very frequently, so your particular tutorials are outdated already.
But I want to answer on your question anyway, because I just spent couple hours in fixing the same issue with new pipeline, and want to share my solution and hope it will be helpful for someone.
Everything works for:
Django==1.9.1
django-pipeline==1.6.4
settings.py
INSTALLED_APPS = (
.
.
'django.contrib.staticfiles',
'pipeline',
'polls',
)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_files')
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'pipeline.finders.PipelineFinder',
)
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
PIPELINE = {
'CSS_COMPRESSOR': 'pipeline.compressors.cssmin.CSSMinCompressor',
'CSSMIN_BINARY': 'cssmin',
'JS_COMPRESSOR': 'pipeline.compressors.slimit.SlimItCompressor',
'STYLESHEETS': {
'pollsX': {
'source_filenames': (
'style.css',
),
'output_filename': 'css/styles1.css',
'variant': 'datauri',
},
},
'JAVASCRIPT': {
'pollsX': {
'source_filenames': (
'script.js',
),
'output_filename': 'js/scripts1.js',
},
}
}
polls.html
{% load pipeline %}
{% stylesheet 'pollsX' %}
{% javascript 'pollsX' %}
<div class='red-me'>
<h1> Hi! I'm a templ! </h1>
</div>
I think you misspelled your css file name.
Instead of using:
<link href="/static/styles1.css" rel="stylesheet" type="text/css" />
Use:
<link href="/static/style.css" rel="stylesheet" type="text/css" />
Related
So I am working on a django datascience project tutorial from this guy's youtube channel: https://github.com/pyplane/django_with_data_science and I'm stuck at getting my static CSS file to apply to my html view.
here is my file structure:
So far, I've been able to get static_project/main.js to work fine but I cannot get the style.css file to work.
style.css
.test_blue_2 {
color:blue;
}
css_test.html
{% load static %}
<link rel='stylesheet' type='text/css' href={% static 'style.css' %}>
<style type = 'text/css'>
.test_blue_1 {
color:blue;
}
</style>
{% block content %}
<div class ='test_blue_1'>Blue text 1</div>
<div class ='test_blue_2'>Blue text 2</div>
{% endblock %}
This outputs Blue text 1 in blue and Blue text 2 remains black
Settings:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static_project'),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "static_root")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "media_root")
http://127.0.0.1:8000/static/style.css yields
.test_blue_2 {
color:blue;
}
here is my file structure:
It seems that my static file doesn't work properly in my django project. I'm not sure whether this is exactly related to js files or the whole static file. Checking related questions, I couldn't find how to solve this problem. So, I send what my template should look like and how it looks in my browser in the below screenshots:
what my template should look:(when scrolling down, the background image also moves)
But this is how my browser shows the template: (no background images, no padding adjustments)
This is my base.html codes:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- Font Awesome -->
<link rel="stylesheet" href="{% static 'css/all.css' %}">
<!-- Bootstrap -->
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
<!-- Custom -->
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<!-- LightBox -->
<link rel="stylesheet" href="{% static 'css/lightbox.min.css' %}">
<title>BT Real Estate</title>
</head>
<body>
<!-- Top Bar -->
{% include 'partials/_topbar.html' %}
<!-- Navbar -->
{% include 'partials/_navbar.html' %}
<!--- Main Content -->
{% block content %} {% endblock %}
<!-- Footer -->
{% include 'partials/_footer.html' %}
<script src="{% static 'js/jquery-3.3.1.min.js' %}"></script>
<script src="{% static 'js/bootstrap.bundle.min.js' %} "></script>
<script src="{% static 'js/lightbox.min.js' %} "></script>
<script src="{% static 'js/main.js' %} "></script>
</body>
</html>
Also, this is how I addressed my static file in settings.py:
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'listings.apps.ListingsConfig',
'realtors.apps.RealtorsConfig',
'pages.apps.PagesConfig',
'django.contrib.auth',
'django.contrib.humanize',
'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 = 'btre.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',
],
},
},
]
WSGI_APPLICATION = 'btre.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': '******',
'USER': '******',
'PASSWORD': '******',
'HOST': 'localhost',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/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.0/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.0/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'btre/static')
]
# Media Folder Settings
MEDIA_ROOT = os.path.join (BASE_DIR, 'media')
MEDIA_URL ='/media/'
Here is my urls.py codes:
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('', include('pages.urls')),
path('listings/', include('listings.urls')),
path('admin/', admin.site.urls),
] + static (settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
Here is how I extend base.html in index.html: (I just brought the show case's codes here)
{% extends 'base.html' %}
{% load humanize %}
{% block content %}
<!-- Showcase -->
<section id="showcase">
<div class="container text-center">
<div class="home-search p-5">
<div class="overlay p-5">
<h1 class="display-4 mb-4">
Property Searching Just Got So Easy
</h1>
<p class="lead">Lorem ipsum dolor sit, amet consectetur adipisicing elit.Recusandae quad,
asperiores eveniet vel nostrum magnam
voluptatum tempore! Consectetur, id commodi!</p>
<div class="search">
<form action="search.html">
<!-- Form Row 1 -->
#pass
{% endblock %}
And finally, here is the hierarchy of my static file:
Why did such a problem happen? Can somebody help me out with this problem?
Thank you.
I think you have to include in your settings a media root and a media url. I use the following settings.
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [os.path.join(BASE_DIR),'static']
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root')
Also then in your URLS, make sure you have the following settings:
(first import static and settings), then enter the following code at the end!
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I think this might fix the problem if the images that aren't displaying are on your local machine.
Just remove the "/cover" and put just "fixed" instead of "fixed/cover" from the "main_app/static/css/style.css/showcase"
My css file is not getting loaded in the webpage. I have css and image file in the same location. The image is getting loaded but not the css.Also I have included the directory in staticfile_dirs.
Setting.py
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'technicalCourse.apps.TechnicalcourseConfig',
'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 = 'website.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
r'C:\Users\Kesavan\PycharmProjects\Django web development\website\technicalCourse\template'
],
'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 = 'website.wsgi.application'
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
r'website\technicalCourse\static',
]
This the template file
<!DOCTYPE html>
{% load static %}
<head>
<link rel="stylesheet" type="text/css" href="{% static 'css/simple.css' %}">
</head>
<body>
<img src="{% static 'image/img.png' %}">
<h1>Welcome to course on programming</h1>
<ol>
{% for x in ac %}
<li>{{x.courseName}}</li>
{% endfor %}
</ol>
</body>
For testing I simply change the color of the h1 tag alone. The css file.
h1{
color:black;
}
Structure
C:.
├───migrations
│ └───__pycache__
├───static
│ ├───css
│ └───image
├───template
│ └───technicalCourse
└───__pycache__
But there is no reflection on the webpage.
Hoping for the solution.
Thanks in advance.
try this command:
python manage.py collectstatic
and check again.
It's weird that images are working and CSS isn't. There could be a multitude of possibilities for your problem.
The simplest way to solve this is to set the path to the CSS files via an absolute or a relative path.
Relavtive path case
<link href="/static/ui/css/base.css" rel="stylesheet">
I was suffering with same problem but solved by adding the
{% load static %}
{
<link rel="stylesheet" type="text/css" href="{% static 'thumbnail_searcher/style.css' %}">
}
in same tag. For example in your case add load and link into <head> tag.
clear browser cache
in settings.py change STATIC_URL = "static/" to STATIC_URL = "/static/"
run python manage.py runserver port_number(optional)
Try
$ python manage.py findstatic css/style.css
instead of css/style.css add your own path
If Django project able to locate the CSS, it will return path to your CSS file.
Then restart your project and it should work.
I am currently making a Web App using the Django framework and have just started recently. I looked through the Django Documentation and also looked through many tutorials and other answers on StackOverflow but none of them seem to work. When I first placed the link on the HTML page I included the {% static 'my_app/css/cssFile'%}and also included {% load staticfiles %}. I have also tried including this into my settings file: STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['static'])) but none of these work. Every time I try to run the server, the console keeps saying that the server could not find the resource and that it exited out as a 404.
This is my settings file:
"""
Django settings for WebApp project.
Generated by 'django-admin startproject' using Django 2.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
import posixpath
# 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.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '6-_^kvfdcg&#+_gdf1ub*ood*$fm4vs1m-aw_uw#(2tliu9(d0'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'WebApp',
'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 = 'WebApp.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',
],
},
},
]
WSGI_APPLICATION = 'WebApp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/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.0/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.0/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.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['static']))
My very simple HTML file that I am using for testing:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }} - My Django Application</title>
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'WebApp/css/layout.css' %}">
</head>
<body>
<div class="navbar clearfix">
<div class="container">
<div class="logo"></div>
<div class="menu-item">
<ul class="item-list">
Home
About
Question
</ul>
</div>
</div>
</div>
<div class="content">
<div class="container-content">
{% block content %}{% endblock %}
</div>
</div>
{% block scripts %}{% endblock %}
</body>
</html>
And the CSS file that I made:
div.navbar {
width: 100%;
color: #FFF;
height: 10px;
background-color: #000000;
}
.clearfix {
content: "";
clear: both;
display: table;
}
.container {
background-color: #000;
width: 100%;
height: 100%;
}
I have set up my directories as follows:
Any help would be greatly appreciated.
Check this im using this now and works.
Settings
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,"media")
and i call in this way
<link href="{% static 'app/vendor/bootstrap/css/bootstrap.min.css'%}" rel="stylesheet">
in urls
if settings.DEBUG:
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Change the next template tag:
{% load staticfiles %}
for:
{% load static %}
Since I started using the Django framework I noticed that the CSS style did not appear when I entered the admin site and others templates and I thought it was normal but with the passage of time I have seen that the applications of my partners did have the style, so I copied their projects on my laptop and I ran them and I could see the CSS style of their applications.
I'm getting data from a database from a server, that's the only difference in how my partners and I have been working.
Does anyone know how I can fix this?
PD: I'm working with version 1.8 of Django and version 3.4.4 of python
This is my base of my HTML's code
{% load staticfiles %}
<html>
<head>
<title>DENUE INEGI</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="{% static 'css/crm.css' %}">
</head>
<body>
<div class="page-header">
{% if user.is_authenticated %}
{% else %}
<span class="glyphicon glyphiconlock"></span>
{% endif %}
<h1>Directorio Estadístico Nacional de Unidades Económicas INEGI</h1>
</div>
<div class="content container">
<div class="row">
<div class="col-md-8">
{% block content %}
{% endblock %}
</div>
</div>
</div>
</body>
</html>
Here is my setting.py file
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',
],
},
},
]
# 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')
LOGIN_REDIRECT_URL = '/'
I appreciate your answers, thank you :)
Try to change Debug = True in your application settings and then check the admin panel.
According to this documentation to serve static files during development you have to:
1) define STATIC_URL in settings file - you have it. So you have to create static folder in the root of your project.
2) STATIC_ROOT = os.path.join(BASE_DIR, 'static')
3) In urls.py of you project you have to have this snippet:
from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
...
]
+ static(settings.STATIC_URL, document_root=settings.STATICFILES_DIRS) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
If your project under deployment, then you can serve static files by the web server. Then you don't need snippet in urls.py
Hope it helps you
Check your urls.py with urls.py of your friends project. I had the same problem with CSS files. and found answer in the docs https://docs.djangoproject.com/en/1.8/howto/static-files/#serving-static-files-during-development