I am trying to render static image files with Django and this is the first time I have encountered images referenced with the
<div style="background-image: url;"></div>
style tag.
I will upload the code and the site as is showing when I run the server.
<div >
<div style="background-image: url('/static/images/doc-1.jpg');"></div>
<div >
<h3 >Dr. Zen Goode</h3>
<span >CEO, Founder</span>
</div>
</div>
This is what the output shows when I run the server. (Of course, it shows other image files here but I assume its just the same):
[22/Jul/2022 06:04:36] "GET /static/images/person_2.jpg HTTP/1.1" 404 1816 django.core.exceptions.SuspiciousFileOperation: The joined path (S:\maps.googleapis.com\maps\api\js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false) is located outside of the base path component (C:\Wor\dentistt\dentist\static)
[22/Jul/2022 06:04:36] "GET /static/images/doc-4.jpg HTTP/1.1" 404 1807
[22/Jul/2022 06:04:36] "GET /static/images/person_1.jpg HTTP/1.1" 404 1816
[22/Jul/2022 06:04:36] "GET /static/images/person_3.jpg HTTP/1.1" 404 1816
[22/Jul/2022 06:04:36] "GET /static/website/https:/maps.googleapis.com/maps/api/js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false HTTP/1.1" 500 59
[22/Jul/2022 06:04:36] "GET /static/images/person_4.jpg HTTP/1.1" 404 1816
[22/Jul/2022 06:04:36] "GET /static/images/image_3.jpg HTTP/1.1" 404 1813
[22/Jul/2022 06:04:36] "GET /static/images/image_1.jpg HTTP/1.1" 404 1813
[22/Jul/2022 06:04:36] "GET /static/images/image_2.jpg HTTP/1.1" 404 1813
I know that with the 404 error, the files are not being found so how I can render the image correctly here?
CodePudding user response:
It seems like you have issue with serving static file. there are two ways
In production it's always good idea to serve static file through any server like nginx or apache using reverse proxy.
for developement
from django.conf import settings
from django.conf.urls.static import static
# Add static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns = [
# ... the rest of your URLconf goes here ...
] static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
On your settings.py
file:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"), # your static/ files folder
]
STATIC_ROOT=os.path.join(BASE_DIR, "static_root")
run the python manage.py collectstatic
CodePudding user response:
in order to display static directory image to your template you have to do couple of things.
go to your project settings.py file and do the following:
STATIC_DIR=(Path(file).parent).joinpath(BASE_DIR,'static')
scroll all the way down of your settings.py file and below STATIC_URL='/static/ write:
STATICFILES_DIRS=[STATIC_DIR,]
in your template/yourhtmlfile.html add following at the top of your .html file
{% load static %}
<script>
var image_one={% static '/images/doc-1.jpg' %}
<div style="background-image: url(image_one);"></div