Django not loading CSS? - html

This is my urls.py
import os.path
site_media = os.path.join(
os.path.dirname(__file__), 'site_media'
)
urlpatterns = patterns('',
url(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{ 'document_root': site_media }),
)
My site_media folder and style.css file is in
myProjectFolder/myApp/static/site_media/css/style.css
and in my base.html template (all my other templates extend off of this base.html template) this is what I have:
<head>
<title>{% block title %}{% endblock %}</title>
<link rel='stylesheet' type='text/css' href='/site_media/css/style.css' />
</head>
<body>
{% block header %}{% endblock %}
{% block content %}
<div id='header'></div>
{% endblock %}
</body>
and in my style.css, all I have is this:
#header {
display: inline;
background-color: black;
color: black;
border: 1px solid green;
}
and the CSS is not being applied to the
#header
div. Any idea why?

The problem comes from 2 areas.
wrong document_root variable passed
not using template tags in html
1.
Defining site_media variable in urls.py file is discouraged as it does not adhere to DRY principle. It should be held as a variable in your settings.py file so other modules may import if needed.
In your settings.py file, add the following line:
import os.path
SITE_MEDIA_ROOT = os.path.join(
os.path.dirname(__file__), 'myApp/', 'static/', 'site_media' #this should be the correct path instead
)
Replace your urls.py file with this:
from myApp import settings
urlpatterns = patterns('',
url(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{ 'document_root': settings.SITE_MEDIA_ROOT }),
)
2.You should use django template tags to get the css file. In your base template, add this line above the head tag:
{% load static %}
Then replace:
<link rel='stylesheet' type='text/css' href='/site_media/css/style.css' />
with:
<link rel='stylesheet' type='text/css' href="{% static 'site_media/css/style.css' %}" />
After which it should work.

Two options:
You can modify a little bit your code in urls.py
in urls.py
site_media = os.path.join(
os.path.dirname(__file__), 'site_media'
)
to
site_media = os.path.join(
os.path.dirname(__file__), "../", "myApp", "static", 'site_media'
)
2. Remove
site_media = os.path.join(
os.path.dirname(__file__), 'site_media'
)
and add
{% load static %} at the beginning of base.html
and change
<link rel='stylesheet' type='text/css' href='/site_media/css/style.css' />
to
<link rel='stylesheet' type='text/css' href="{% static 'site_media/css/style.css' %}" />
The second method is preferable.
Here is working code: https://github.com/lukaszszajkowski/s21083672
Here are links to documentation and reading:
https://docs.djangoproject.com/en/dev/howto/static-files/#configuring-static-files
Media files are served, static files aren't

Related

Django won't resolve path to static file inside VS Code editor

The {% load static %} tag at the top of my html file seems to work
But when I try to link my css file from static folder using this code :
{% load static %}
<link href="{% static 'static/style.css' %}" rel="stylesheet">
vscode tries to create a file called {% static 'static/style.css' %} inside my templates directory, meaning the static keyword isn't being recognized.
Any help in figuring out why would be highly appreciated (screenshot of path at bottom)
Here's my relevant settings.py to link static files
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR / "static",
'/Google_Solutions/static/',
]
My static and templates are in the main directory
and here's my home.html file head where i'm trying to include files
{% extends 'layout.html' %}
{% load static %}
{% block head %}
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<title> Homepage </title>
<!-- Template Main CSS File -->
{% load static %}
<link href="{% static 'css/style.css' %}" rel="stylesheet">
{% endblock %}
here's my layout.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="icon" type="image/png" sizes="16x16" href="{% static '/favicon-16x16.png'%}">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Dancing+Script:wght#700&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Lobster&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght#300&display=swap" rel="stylesheet">
{% block head %}
{% endblock %}
</head>
<body>
{% block body %}
{% endblock %}
</body>
<script type="text/javascript" src="{% static 'js/app.js' %}"></script>
So I found out the error , it was only my local vscode
Even if the hover link shows the wrong address, as long as your syntax is correct, your static files will load just fine. Check it by starting your server

python3 manage.py findstatic can't find static file

I am trying to add static file to my project but css doesn't load. I used findstatic but django doesn't see any static directory:
In another project django still can find static folder:
My settings.py:
STATIC_URL = '/static/'
My base.html:
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<link href = "{% static 'css/base.css' %}" rel = 'stylesheet'>
<title>{% block title %}Educa{% endblock %}</title>
</head>
<body>
<div id = 'header'>
<a href = "/" class = 'logo'>EDUCATION</a>
<ul class = 'menu'>
{% if request.user.is_authenticated %}
<li>Logout</li>
{% else %}
<li>Login</li>
{% endif %}
</ul>
</div id ='content'>
{% block content %}{% endblock %}
<script src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/
jquery.min.js'></script>
<script>
$(document).ready(function(){
{% block domready %}
{% endblock %}
});
</script>
</body>
</html>
Thank you
I don't know how it even possible but i tried to rename my static folder and i found out there was an space after 'static'. After that css loaded BUT not for this project. It was css from another environment so i renamed it to main.css from base.css and also changed:
<link href = "{% static 'css/main.css' %}" rel = 'stylesheet'>
and everything works fine. Thank you all for help, interesting experience, sorry)

CSS isn't loading to style HTML-connected to static in Django

So basically I can't manage to connect .css file to my .html.
Previously it just wasn't finding the .css file but after I've referenced the full path it stopped giving me the 'not found' error on cmd local host so it does find it it just doesn't apply it to change styling.
The .html and .css files are in the same folder, I already tried putting the css in both /static and /media folders, neither worked
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href=C:\Users\Any1\Desktop\personal_portfolio-
project\blog\templates\blog\master.css">
</head>
<body>
<h1>Example heading</h1>
<p>Lori is home blog</p>
</body>
</html>
#just trying to change h1 color to red for testing
h1 { color: #FF0000;
}
#and my settings.py
STATIC_URL = '/static/'
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'
#Mark Rofail
thanks so much that fixed it.
I just did
{% load static %}
<link href="{% static 'css/master.css' %}" rel="stylesheet">
instead of
<link rel="stylesheet" href=C:\Users\Any1\Desktop\personal_portfolio-
write it like this
{% load static %}
.
.
.
{% block css %}
<link href="{% static 'css/master.css' %}" rel="stylesheet">
{% endblock %}
make sure your css is at '/static/css/master.css'

Html does not import css file

Silly question but i can't figure it out and it's too much. In a django project, in the same directory i have base_template.html and base_style.css. In a child folder i have search.html.
base_template.html
base_style.css
folder----
search.html
Search.html extends base_template.html like so
{% extends "base_template.html" %}
Inside base_template.html i import base_style.css
<!DOCTYPE html>
<html>
<head>
<title>{% block title %} Base template {% endblock %}</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="base_style.css">
<link rel="stylesheet" type="text/css" href="awesome_font.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat">
<style>
{% block Additional_Styles %}
{% endblock %}
</style>
And there's no way it works.
**Already tried:
./base_style.css
/base_style.css
base_style.css"/**
If i replace
<link rel="stylesheet" type="text/css" href="base_style.css">
with:
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
It works, the css loads. I must mention that i just downloaded the css from the link and made no modifications.
Why doesnt the import work?
EDIT
settings.py:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
....
STATIC_URL = '/static/'
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
So the base_template is in MainDjangoApp\templates
You should pu your static files (.css, .js) in a static folder inside your app:
app
static
app
css
base_style.css
adn in your template you should use
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'app/css/base_style.css' %}">
You should definitely read Writing your first Django app, part 6 and Managing static files (e.g. images, JavaScript, CSS) on the djangoproject site.
A solution would have been to change the folder of base_style.css as in the docs, however i added this to settings.py and i got it working. My app is not that complex so i won't get tangled in files.
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "templates"),
]

Code 404 when fetching image in Django template

I am trying to fetch some images located in a folder. The path is correct but they appear as broken link with code 404.
MY files and configurations are as follows:
settings.py
MEDIA_ROOT = os.path.join( PROJECT_DIR, 'media/images/uploads')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = '/media/images/uploads/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = os.path.join( PROJECT_DIR, 'static')
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
'C:\Users\omars_000\Desktop\mytask\mytask\media\images',
'C:\Users\omars_000\Desktop\mytask\mytask\media\images\uploads',
'C:\Users\omars_000\Desktop\mytask\mytask\media',
)
models.py
class Pics(models.Model):
name = models.CharField(max_length=200, null=True)
docfile = models.ImageField(upload_to=content_file_name, null=True, blank=True)
def __unicode__(self): # Python 3: def __str__(self):
return self.docfile
home.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
{% load staticfiles %}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Home Page</title>
<link href="{{ STATIC_URL }}styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="background">
Value of a is {{ imgs.0 }}
<div id="background"><img src="{% static "images\background.png" %}""></div>
<div id="Shape17copy"><img src="{% static "images\Shape17copy.png" %}""></div>
<div id="About"><img src="{% static "images\About.png" %}""></div>
<div id="Layer7">
<img src="{% static "images\Layer7.png" %}"">
{% if imgs %}
{% for i in imgs %}
<img src="{{i.docfile.url}}"/>
{% endfor %}
{% else %}
{% endif %}
</div>
<div id="Layer7copy"><img src="{% static "images\Layer7copy.png" %}""></div>
<div id="Shape17copy2"><img src="{% static "images\Shape17copy.png" %}""></div>
<div id="RecentWork"><img src="{% static "images\RecentWork.png" %}""></div>
</div>
</body>
</html>
What could be my issue?!
I have also faced this problem but it worked when I used hard coded URLs like this
<img src="/static/images/background.png" />
And moreover use forward slash
Have you tried forward slashes for the image paths in the {% static %} tags?
Update: check the syntax of your static tags: use single quotes for the filename inside the tag and fix the incorrect extra double quote at the end of each img tag