Django - unable to load static files? - django

Very new to Django I am trying to follow along a tutorial by sentdex over on youtube.
Django version 1.9
Chose this version as that is being used in the tutorial.
I can't seem to figure out how to get the css file to load.
The location of the css file
/media/xxx/django tutorial/mysite/personal/static/personal/css
I assume the BASE_URL is referencing till:
/media/xxx/djangotutroial/mysite
This is the location of the manage.py. Or am I wrong?
The css file is reference in header.html:
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'personal/css/bootstrap.min.css' %}" type = "text/css"/>
I read through a lot of the answers and if I understand correctly I have to change settings.py in mysite folder.
This is what I have at the moment:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'personal'),
]
I have tried a lot of combinations in the os.path.join I still can't get the file to load.
Thank for your help.
Project Structure:
django tutorial
--mysite
--mysite
---------__pycache_
---------__init__.py
---------settings.py
---------urls.py
---------wsgi.py
--personal
---------migrations
---------__pycache_
---------static
------personal
------css # has the bootstrap.min.css
------js
---------templates
---------admin.py
---------apps.py
---------init.py
---------models.py
---------tests.py
---------urls.py
---------views.py
If someone can tell me the right command to get the directory structure in ubuntu I would be happy to show that here.
Template:
In home.html:
{% extends "personal/header.html" %}
{% block content %}
<p>Hey, welcome to my webpage. We are testing.<p>
{% include "personal/includes/htmlsnippets.html" %}
{% endblock %}
Error message in view page source
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Page not found at /static/personal/css/bootstrap.min.css</title>
<meta name="robots" content="NONE,NOARCHIVE">
<style type="text/css">
html * { padding:0; margin:0; }
body * { padding:10px 20px; }
body * * { padding:0; }
body { font:small sans-serif; background:#eee; }
body>div { border-bottom:1px solid #ddd; }
h1 { font-weight:normal; margin-bottom:.4em; }
h1 span { font-size:60%; color:#666; font-weight:normal; }
table { border:none; border-collapse: collapse; width:100%; }
td, th { vertical-align:top; padding:2px 3px; }
th { width:12em; text-align:right; color:#666; padding-right:.5em; }
#info { background:#f6f6f6; }
#info ol { margin: 0.5em 4em; }
#info ol li { font-family: monospace; }
#summary { background: #ffc; }
#explanation { background:#eee; border-bottom: 0px none; }
</style>
</head>
<body>
<div id="summary">
<h1>Page not found <span>(404)</span></h1>
<table class="meta">
<tr>
<th>Request Method:</th>
<td>GET</td>
</tr>
<tr>
<th>Request URL:</th>
<td>http://127.0.0.1:8000/static/personal/css/bootstrap.min.css</td>
</tr>
</table>
</div>
<div id="info">
<p>'personal/css/bootstrap.min.css' could not be found</p>
</div>
<div id="explanation">
<p>
You're seeing this error because you have <code>DEBUG = True</code> in
your Django settings file. Change that to <code>False</code>, and Django
will display a standard 404 page.
</p>
</div>
</body>
</html>
In the terminal where runserver:
[24/Feb/2019 06:19:32] "GET /static/personal/css/bootstrap.min.css HTTP/1.1" 404 1703
Error when running using #bkawan code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Page not found at /static/personal/css/bootstrap.min.css</title>
<meta name="robots" content="NONE,NOARCHIVE">
<style type="text/css">
html * { padding:0; margin:0; }
body * { padding:10px 20px; }
body * * { padding:0; }
body { font:small sans-serif; background:#eee; }
body>div { border-bottom:1px solid #ddd; }
h1 { font-weight:normal; margin-bottom:.4em; }
h1 span { font-size:60%; color:#666; font-weight:normal; }
table { border:none; border-collapse: collapse; width:100%; }
td, th { vertical-align:top; padding:2px 3px; }
th { width:12em; text-align:right; color:#666; padding- right:.5em; }
#info { background:#f6f6f6; }
#info ol { margin: 0.5em 4em; }
#info ol li { font-family: monospace; }
#summary { background: #ffc; }
#explanation { background:#eee; border-bottom: 0px none; }
</style>
</head>
<body>
<div id="summary">
<h1>Page not found <span>(404)</span></h1>
<table class="meta">
<tr>
<th>Request Method:</th>
<td>GET</td>
</tr>
<tr>
<th>Request URL:</th>
<td>http://127.0.0.1:8000/static/personal/css/bootstrap.min.css</td>
</tr>
</table>
</div>
<div id="info">
<p>'personal/css/bootstrap.min.css' could not be found</p>
</div>
<div id="explanation">
<p>
You're seeing this error because you have <code>DEBUG = True</code> in
your Django settings file. Change that to <code>False</code>, and Django
will display a standard 404 page.
</p>
</div>
</body>
</html>

Please check if you have done first step as below
Official Documentation link for Django 1.9 link
This document is for an insecure version of Django that is no longer
supported. Please upgrade to a newer release!
Try to move on new release since documentation 1.9 is no longer supported.
Configuring static files
Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.
Check If your folder structure is similar as below
Project Structure image Link
You do not need to add code below unless if personal folder is same level as BASE_DIR
os.path.join(BASE_DIR,'personal')
Your code below is fine if you have personal app and then static folder inside personal app and then personal folder inside static folder ie personal/static/personal
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'personal/css/bootstrap.min.css' %}" type = "text/css"/>
In Case if Page not found error.
Check if bootstrap.min.css exists in path personal/css/bootstrap.min.css
Check spelling as well.
Check your app ie personal in this case is included in INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'personal'
]

You should serve them during development. Check this part.
Edit your main urls.py(you'll find it in same folder as settings.py).
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Make sure that your app is listed in INSTALLED_APPS in django settings.

Remove /personal from your style sheet import. Instead, just have:
{%load static%}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type = "text/css"/>

I am not sure if you copied and pasted exactly the same code but the p closing tag is out of syntax in home.html.

Related

CSS not applied to the HTML page (Django)

index.html
I have changed {% static "/main/css/index.css" %} to {% static "main/css/index.css" %}
{% extends 'main/base.html' %}
{% load static %}
<link rel = 'stylesheet' type="text/css" href="{% static "/main/css/index.css" %}"/>
{% block title %}
{{title}}
{% endblock %}
{% block content %}
<body>
<div class="grid-wrapper">
<header class="grid-header">
<img class="circles" src="{% static "main/img/main8.jpg" %}" alt="main pic">
<p>hello</p>
</header>
</div>
</body>
{% endblock %}
index.css
.grid-wrapper {
display: grid;
grid-template-columns: 1 fr;
grid-template-rows: 1 fr;
grid-template-areas: 'header header';
}
.circles {
display: block;
margin-left: auto;
margin-right: auto;
}
header {
position: relative;
width: 100%;
}
p {
color: red;
text-align: center;
position: absolute;
width: 100%;
text-align: center;
top: 0;
}
settings.py
STATIC_URL = 'static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "main/static"),
]
I tried changing file names, changing locations, connecting in a different way, but all this does not work. I also changed the settings.
This is an example of my configurations:
settings.py
STATIC_DIR = os.path.join(BASE_DIR,"static")
STATIC_URL = '/static/'
STATICFILES_DIRS = [
STATIC_DIR,
]
base.html
<!DOCTYPE html>
{%load static%}
<html lang="en">
<head>
My file structure is:
/Project
/App
/Project
/settings.py
/static
/styles.css
/templates
/base.html
You may need to share you directory structure to get further clarifications.

Django: How i can delete the white space between the background image and the origin page also Page number appear (Page undefined of undefined)

Am still learning on Django and wkhtml2pdf using and I need some help please, I have searched and try much solutions but they don't work with me, I want to set a background image and page number in the footer(I Have use wkhtml2pdf library):
Here it's the code
<!doctype html>
<html lang="en">
<head>
<style type="text/css">
body{
background-image: url('data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/...');
margin:0px;
background-size: cover;
background-position: left top;
padding-top:0px;
height: 1100px;
width: 900px;
}
#divb
{
font-size: 12px;
font-family: Arial;
}
div.footer {
display: block; text-align: center;
position: running(footer);
#page {
#bottom-center { content: element(footer) }
}
}
</style>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body style="border:0; margin: 0;">
<div id="divb">
<p><strong>Materials :</strong> {{ materiel }}</p>
.........(the rest of calling the data)
</div>
<div class='footer'>
Page <span id='page'></span> of
<span id='topage'></span>
<script>
var vars={};
var x=window.location.search.substring(1).split('&');
for (var i in x) {
var z=x[i].split('=',2);
vars[z[0]] = unescape(z[1]);
}
document.getElementById('page').innerHTML = vars.page;
document.getElementById('topage').innerHTML = vars.topage;
</script>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
<script>
window.load = function() {
window.status = 'render-pdf';
};
</script>
</body>
</html>
and here it's the result :
the was a white space between the background image and the origin page , also the number of page appear to me (Page undefined of undefined), How i can adjust the background-image correctly to filled out all the page without white space , also what' wrong with page number in the footer.
see the screenshoot please.
enter image description here
.Thanks In Advance for everyone here.

Django - links are incorrectly resolved in menu

I am developing locally Django page and have some issues with highlighted menus.
when hover over "moje projekty" I see below link
127.0.0.1:8080/portfolio/, I click and page opens
when now I hover hover 2nd time, it is showing:
127.0.0.1:8080/portfolio/portfolio/, I click and page opens
when now I hover hover 3rd time,it is showing:
127.0.0.1:8080/portfolio/portfolio/portfolio/, I click and error is:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8080/portfolio/portfolio/portfolio/
Using the URLconf defined in my_site.urls, Django tried these URL patterns, in this order:
admin/
[name='home']
about_me/ [name='aboutme']
portfolio/ [name='portfolio']
posts/<slug:the_slug>/ [name='post_detail']
summernote/
^media/(?P<path>.*)$
portfolio/ [name='home']
portfolio/ about_me/ [name='aboutme']
portfolio/ portfolio/ [name='portfolio']
portfolio/ posts/<slug:the_slug>/ [name='post_detail']
portfolio/ summernote/
portfolio/ ^media/(?P<path>.*)$
about_me/
The current path, portfolio/portfolio/portfolio/, didn’t match any of these.
base.html:
<!DOCTYPE html>
<html>
<head>
<title>Moja strona</title>
<link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet">
<meta name="google" content="notranslate" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous" />
</head>
<body>
<style>
body {
font-family: "Roboto", sans-serif;
font-size: 17px;
background-color: #fdfdfd;
}
.shadow {
box-shadow: 0 4px 2px -2px rgba(0, 0, 0, 0.1);
}
.btn-danger {
color: #fff;
background-color: #f00000;
border-color: #dc281e;
}
.masthead {
background: #3398E1;
height: auto;
padding-bottom: 15px;
box-shadow: 0 16px 48px #E3E7EB;
padding-top: 10px;
}
img {
width: 00%;
height: auto;
object-fit: contain;
</style>
{% load static %}
<center> <img src="{% static 'blog/moj.png' %}" alt="My image"> </center>
<!-- Navigation -->
<nav class="navbar navbar-expand-sm navbar-light bg-light shadow" id="mainNav">
<div class="container-fluid">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive"
aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item text-black">
<a class="nav-link text-black font-weight-bold" href="/">Blog</a>
</li>
<li class="nav-item text-black">
<a class="nav-link text-black font-weight-bold" href="portfolio/">Moje projekty</a>
</li>
<li class="nav-item text-black">
<a class="nav-link text-black font-weight-bold" href="about_me">Kontakt</a>
</li>
</ul>
</div>
</div>
</nav>
{% block content %}
<!-- Content Goes here -->
{% endblock content %}
<!-- Footer -->
</body>
</html>
urls.py project:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
path('portfolio/', include('blog.urls')),
path('about_me/', include('blog.urls')),
]
urls.py app:
from . import views
from django.urls import path
from django.conf.urls import include
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('about_me/', views.Aboutme.as_view(), name='aboutme'),
path('portfolio/', views.Portfolio.as_view(), name='portfolio'),
path('posts/<slug:the_slug>/', views.PostDetail.as_view(), name='post_detail'),
path('summernote/', include('django_summernote.urls')),
]
# to jest dla wysiwyg
# add condition in django urls file
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
Questions:
why link is changing 2nd time when I click?
why I am getting this error after 3rd click?
Hey :) the paths /portfolio/ and /portfolio/portfolio/ are correct, but when you use htm href='portfolio/' without forward slash they are not absolute. html just add it to existing one. So if u in example.com/portfolio/ and click this href you adds another 'portfolio/'.
just use in href :
<a class="nav-link text-black font-weight-bold" href="{% url 'blog:portfolio' %}">
PS. in urls.py for project you don't need two paths to the same app

base.css is not get imported into the page?

I am trying to override the class generated by page-down app and the django-crispy-forms . But the indentation that is expected through overrideing class is not working.
base.html(initially)
...
<link rel='stylesheet' href='{% static "css/base.css" %}'>
<style>
{% block style %}{% endblock style %}
</style>
{% block head_extra %}{% endblock head_extra %}
...
base.css
h1 {
color: #777777;
}
post_forms.html
{%extends "base.html" %}
{% load crispy_forms_tags %}
{% block head_extra %}
{{form.media}}
{% endblock head_extra %}
...
By using the inspect feature in chrome I can spot the class that causes the indentation
<div class="wmd-panel">
</div>
The code CSS given below is automatically generated one
.wmd-panel {
margin-left: 25%;
margin-right: 25%;
width: 50%;
min-width: 500px;
}
But after making changes to css/base.css , there is no class named wmd-panel from the file base.css in the styles tab of the chrome. And the changes made are not reflected in the webpage.
base.css
h1 {
color: #777777;
}
.wmd-panel{
margin-right: 0px !important;
margin-left: 0px !important;
}
This is what expected in chrome inspect styles tab
.wmd-panel {
margin-left: 0%;
margin-right: 0%;
}
This above class is from basic.css
You should clean the chrome cache and check again. Sometimes it just does not update the code and you are just viewing the old CSS even you have made changes to it.
Settings>Advanced>ClearBrowsingData>
and delete all Cached images and files
Do you have {% load static %}? Sometimes you just forget that. And often you miss STATIC_URL = '/static/' in your settings.

Django + Anymail + Mailgun - Email HTML renders without button and image

I am having an issue while trying to send an email containing html and an image, through mailgun, using the anymail library.
This is my code:
url_formulario = CLIENT_URL + str(token.key)
email = EmailMultiAlternatives('Confirmación Vacante', to=emails)
cid = attach_inline_image_file(email, '/var/www/static/icons/ba_logo.png')
contexto = {'nombre_contacto': contacto.responsable_nombre,
'nombre_alumno': contacto.alumno_nombre,
'url_formulario': url_formulario,
'imagen':cid}
mensaje = render_to_string('email.html', context=contexto)
email.attach_alternative(mensaje, "text/html")
email.track_clicks = True
email.send()
I have also tried doing it like this:
url_formulario = CLIENT_URL + str(token.key)
contexto = {'nombre_contacto': contacto.responsable_nombre,
'nombre_alumno': contacto.alumno_nombre,
'url_formulario': url_formulario}
mensaje = render_to_string('email.html', context=contexto)
content = strip_tags(mensaje)
email = EmailMultiAlternatives('Confirmación Vacante', content,to=emails)
email.attach_alternative(mensaje, "text/html")
email.track_clicks = True
email.send()
Here are the two corresponding versions of the html file I am using:
<html>
<head>
<title>Ingresa al formulario</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Bastrap CSS -->
<link rel="stylesheet" href="/static/css/bastrap.css">
<style>
.contenedor-general{
background:#e5e5e5;
padding-top:3em;
}
.contenedor-general img{
padding-bottom:3em;
}
.contenido-mensaje{
background:white;
margin-bottom:calc(43px + 6em);
}
.contenido-mensaje p{
font-family:"CHANEWEI", Helvetica, Arial, sans-serif;
margin:7%;
color:#717170;
}
.contenido-mensaje h1,
.contenido-mensaje a{
margin: 0 7% 0 7%;
}
.contenido-mensaje h1{
padding-top:7%;
color:#717170;
}
.contenido-mensaje a{
color:#333;
}
.btn-primary{
background-color:#fcda59 !important;
color:#685723 !important;
box-shadow:none !important;
}
.btn-primary:hover{
background-color:#fdd306 !important;
border-color:#fdd306 !important;
color:#685723 !important;
box-shadow:none !important;
}
</style>
</head>
<body>
<div class="container">
<div class="contenedor-general col-lg-8 col-lg-offset-2">
<img src="{{imagen}}" alt="Logo Buenos Aires" class="center-block"/>
<div class="col-lg-8 col-lg-offset-2 contenido-mensaje">
<h2>Hola {{nombre_contacto}},</h2>
<p>Tenemos una vacante escolar pendiente para {{nombre_alumno}}</p>
Confirmar vacante
<p>Si tenés problemas para ingresar comunicate al XXXX-XXXX (Número de télefono)</p>
<p>Muchas gracias</p>
</div>
</div>
</body>
</html>
Another version of the tag without passing the image:
<img src="" alt="Logo Buenos Aires" class="center-block"/>
This is the resulting email:
Is there a way to attach an html file after rendering it to a string with an specified context and an image attached?
Thanks.
It looks like your template is missing the cid: part of the <img src>. You have:
<img src="{{imagen}}" alt="Logo Buenos Aires" class="center-block"/>
But that would need to be:
<img src="cid:{{imagen}}" alt="Logo Buenos Aires" class="center-block"/>
The cid: scheme is how the email client knows to treat the value of {{imagen}} as an inline Content-ID. Without it, the client doesn't know where it's supposed to look for that image source, so you get a broken image icon instead.
There's a little more detail in the Anymail docs