Code 404 when fetching image in Django template - html

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

Related

Django does not call the function and does not output information from the database

I started learning django recently and am writing a website for a tutor. I need to add output to topics that are entered into the database through the admin panel. But he doesn't take them out. Although the profile data is displayed perfectly.
views.py
class TopicListView(ListView):
model = Topic
template_name = 'video/video.html'
context_object_name = 'top'
def video(request):
top = Topic.objects.all()
context = {'top': top}
return render(request, 'video/video.html', context)
video.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<link rel="icon" href="../static/images/favicon.jpg" type="image/x-icon">
<link rel="shortcut icon" href="../static/images/favicon.jpg" type="image/x-icon">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Материалы</title>
<link rel="stylesheet" href="{% static 'profiles/css/style.css' %}" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
</head>
<body>
{% if user.is_authenticated %}
<div class="top">
Главная
<a class="active" href="video">Материалы</a>
Тесты
Выйти
</div>
{% for post in top %}
<div>
<h3>{{ post.name_topic }}</h3>
</div>
{% endfor %}
{% else %}
<p>Ввойдите в профиль, чтобы увидеть эту страницу</p>
<div class="button">
Log in
</div>
{% endif %}
</body>
</html>
urls.py
from django.urls import path
from . import views
from django.conf.urls import url
urlpatterns = [
path('', views.profiles),
url(r'^video/$', views.video, name='topic'),
path('question', views.question),
]
enter image description here

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'

Django html extends tags

This is my base.html
<!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">
</head>
<body>
{% block content %}{% endblock content %}
</body>
</html>
This is home_page where I am using the {% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="container">
<h1>{{ title }}</h1>
<h1>Hello, world!</h1>
<img src="{% static 'img/myImage.jpg' %}" class='img-fluid'>
</div>
{% if premium_content %}
<div class="row">
<div class="col">
<h1>Premium</h1>
{{ premium_content }}
</div>
{% endif %}
</div>
{% endblock content %}
The here is my views.py where I have the home_page and before using the extends tag I could render this page properly
def home_page(request):
context = {
"title":"Hello World We Working"
}
if request.user.is_authenticated:
context["premium_content"] = 'Only premium users see this'
return render(request, 'MainApp/home_page.html', context)
The error message that I am getting is TemplateDoesNotExist at / Which I do not understand I even tried putting the two html files in the same directory but still I get the same error message
You should create templates file in your project or app directory and update TEMPLATES variable in the settings.py like below:
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR, 'templates')],
...
},
]
And then put your HTML files on the templates directory
I hope this works for you

Django not loading CSS?

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