CSS style is missing in all my Django applications - python

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

Related

django html template can't find static css and js files

I have a django project that structure is like this:
>vira
>vira
-__init.py
-settings.py
-urls.py
-wsgi.py
>vira_app
>migrations
>template
-index.html
>static
>vira_app
>assets
>css
>js
>vendor
>aos
>bootstrap
>bootstrap-icons
>isotope-layout
>swiper
-__init__.py
-admin.py
-apps.py
-models.py
-tests.py
-urls.py
-views.py
-db.sqlite3
-manage.py
I have used bootstrap. index.html is like below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
{% load static %}
<link href="{% static 'vira_app/assets/vendor/aos/aos.css' %}" rel="stylesheet">
<link href="{% static 'vira_app/assets/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
<link href="{% static 'vira_app/assets/vendor/bootstrap-icons/bootstrap-icons.css' %}" rel="stylesheet">
<link href="{% static 'vira_app/assets/vendor/swiper/swiper-bundle.min.css' %}" rel="stylesheet">
{% load static %}
<link href="{% static 'vira_app/assets/css/style.css' %}" rel="stylesheet">
</head>
<body>
<main id="main">
<div id="portfolio-grid" class="row no-gutter" data-aos="fade-up" data-aos-delay="200">
{% if catalogue_list %}
{% for Catalogue in catalogue_list %}
<div class="item web col-sm-6 col-md-4 col-lg-4 mb-4">
<a href="{{ Catalogue.link }}" class="item-wrap fancybox">
<div class="work-info">
<h3>{{ Catalogue.title }}</h3>
<span>{{ Catalogue.source }}</span>
</div>
<img class="img-fluid" src="{{ Catalogue.image }}">
</a>
</div>
{% endfor %}
{% endif %}
</div>
</div>
</main>
<i class="bi bi-arrow-up-short"></i>
<script src="assets/vendor/aos/aos.js"></script>
<script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/isotope-layout/isotope.pkgd.min.js"></script>
<script src="assets/vendor/php-email-form/validate.js"></script>
<script src="assets/vendor/swiper/swiper-bundle.min.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
settings.py:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'vira_app', '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',
],
},
},
]
STATIC_URL = '/static/'
STATIC_ROOT = '/vira_app/template'
When I run the server and go to index.html, data retrieved from db and show well, but without any style!
I have tried some solution, check every static url, but not working
In fact, css, js and vendors not applied. What's the problem?
Some of settings are misused:
STATIC_URL = '/static/' - this is fine
STATIC_ROOT = '/vira_app/template' - nope, this is supposed to be some folder not really related to the project structure. In the end, on prod it can be a CDN URL or a folder on different server. So try changing it to something like STATIC_ROOT = os.path.join(BASE_DIR, 'static') for the start.
As mentioned in comments you might need to define STATICFILES_DIRS - a list of folders where from static files must be collected to STATIC_ROOT by collectstatic command. This means you can have many subfolders containing static files in different places. However you'll need to collect those files all together to deploy somewhere. STATICFILES_DIRS + collectstatic will collect all of those files for you into given STATIC_ROOT (and contents of this folder should be deployed somewhere, to CDN for example).
Note, default set of STATICFILES_FINDERS already contains AppDirectoriesFinder which will automatically find all the static subfolders in any of the project apps. This means if you move static subfolder from templates to the vira_app root - you won't have to mention it in the STATICFILES_DIRS.
So:
STATIC_ROOT should not point to any templates subfolders, change it to something more "global"
STATICFILES_DIRS should link to the folder(s) where you keep your static files now or this folder should be moved to the root of vira_app to let collectstatic find it
collectstatic must be run before checking your styles and scripts in rendered page
after running collectstatic all the static files must persist in STATIC_ROOT so django will be able to map relative urls after STATIC_URL to relative paths after STATIC_ROOT and those files will be loaded
PS
Note, some of your static files are linked in wrong way in the shown template:
<script src="assets/vendor/aos/aos.js"></script>
this should be changed to {% static... as well.

Django - Cannot link static CSS to applications

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:

Django : Import static file inside a template doesn't work properly

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"

I am not able to load the staticfiles in my templates. What am I doing wrong?

I need to incorporate css in my templates to help them look better, but inspite of adding the static url and root, I am just not able to load it in my template. I am attaching the relevant code here. Please tell me what am I doing wrong. Thanks in advance.
settings.py
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')
STATIC_URL = '/static/'
STATIC_ROOT = [STATIC_DIR,],
index.html
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
<link href="{% static 'css/index.css' %}">
</head>
settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'project_name/static')
]
index.html
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<link href="{% static 'css/index.css' %}" rel="stylesheet">
</head>
for more information check here
for loading static files you need to add the static url too
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
......
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
add these in your project's root url
Change url base urls.py like following
urlpatterns = [
# your url here
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Also include {% load static %} tag in your template
There is no settings named STATIC_DIR, it should be STATICFILES_DIRS and should be declared like this:
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR,'staticroot') # Static Dir and Static root needs to be different
As for serving static files, as per documentation, if you add django.contrib.staticfiles in INSTALLED_APPS, then django will serve static automatically when DEBUG is True. But in production, you need to use a reverse proxy server to static files. Or you can use whitenoise. More information can be found in documentation as well.
Which version of Django do you using? Starting from 2.0 there are some changes, instead of
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
there is
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',
],
},
},]
Also check out is your static folder even exist
And be sure that you have chosen right path to your static folder(for example I hold this folder inside of template folder so my code looks like this)
STATIC_URL = '/templates/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "templates/static"),]
And I see that you didn't put csrf_token to your html, so please add this to your html
{% csrf_token %}

Can't get on-server but external css to be used bydjango 1.10

Try as I might, and after trying to read through and follow these (and others):
How do I serve CSS to Django in development?
Django not loading CSS?
I still can't get any staticfiles served by django. at this point, I have a project called limbo, with a yet-to-be-dev'd app called limbo (that was a bad idea, I no realize...name confusion), and a separate app called polls, where I followed well-known django tutorial to build out the app, then added a little session variable passing to pass the name to a stupid output on the target of the form. It's all served on EC2 linux AMI, with django v1.10, I'm viewing it with chrome v53.
some code excertps are below, but the repos are public (one for the bulk of the django, the other for the html templates)
~/limbo/limbo/settings.py:
ROOT_URLCONF = 'limbo.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
'/var/www/html/',
'/var/www/html/polls/',
],
'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.10/howto/static-files/
#STATIC_URL = '/static/'
#STATIC_ROOT = os.path.join(BASE_DIR, "/var/www/html/static/")
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = [
# "/home/ec2-user/limbo/limbo/static/",
]
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
~/limbo/limbo/urls.py:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
entire ~/limbo/polls/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^index.html$', views.index, name='index'),
url(r'^formTest$', views.testForm, name='testForm'),
url(r'^name-test.html$', views.get_name, name='getName'),
url(r'^testFormResults/',
# <string>[\w\-]+)/$',
views.testFormResults,
name='showFormResults'),
]
excerpt from /var/www/html/polls/name.html (which shows fine, but without any css nor img), it does show both when viewing local on my win8.1 surface, but not remotely from the server (note I now have {% load static %} instead and it didn't change anything that I can see):
<!DOCTYPE html>
<html>
{% load staticfiles %}
<head>
<!--this group for local use w/o django-->
<link rel="stylesheet" type="text/css" href="../static/polls/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="../static/polls/css/bootstrap-theme.min.css">
<link rel="stylesheet" type="text/css" href="../static/polls/css/limbo.css">
<!--this group for use w/ django-->
<link rel="stylesheet" type="text/css" href="{% static 'polls/css/bootstrap.min.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'polls/css/bootstrap-theme.min.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'polls/css/limbo.css' %}" />
</head>
<div class="navbar navbar-default navbar-fixed-top">
<div class=container>
<img class="top-bar" src="static/polls/limbo-clipart-1.jpg" alt="limbo graphic"/>
<img src="{% static 'polls/static/limbo-clipart-1.jpg' %}" alt="limbo graphic"/>
<h1>This is a heading</h1>
</div>
</div>
Try as I might, I just can't get past this. I'm excited about getting django up and running as I think it'll be a fantastic way to build the api I need and the little bit of browser-based UI the project needs, but I need a little css to make the browser-UI.

Categories