86👍
Use this:
#third{
background: url("/static/img/sample.jpeg") 50% 0 no-repeat fixed;
color: white;
height: 650px;
padding: 100px 0 0 0;
}
Most probably This will work.Use “/static/” before your image URL and then try them. Thanks
- [Django]-Error: Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>
- [Django]-Django unit tests without a db
- [Django]-ImageField overwrite image file with same name
10👍
For some reasons, which I cannot explain the accepted answer did not worked out for me. (I wanted to use a picture as a cover image for the whole body).
However, here is the alternative that has worked for me for anyone that might be useful for someone that will come across.
In a css file, which is located in the static file directory, I have wrote the following:
CSS:
body {
background: url(../main/img/picture-name.jpg);
}
You do not have to include *'{% load static %}'*
in your css file.
HTML:
-
include
{%load static%}
at the top -
create a link href to style, as below.
<link href='{% static "/main/home.css" %}' rel='stylesheet' type='text/css'>
- [Django]-Django migration with uuid field generates duplicated values
- [Django]-How do I include related model fields using Django Rest Framework?
- [Django]-How to server HTTP/2 Protocol with django
9👍
Make sure that django.contrib.staticfiles
is included in your INSTALLED_APPS.
In you settings.py file define STATIC_URL: STATIC_URL = '/static/'
{% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image"/>
or
#third{
background: url('{{ STATIC_URL }}my_app/example.jpg'
}
- [Django]-No handlers could be found for logger
- [Django]-Coverage.py warning: No data was collected. (no-data-collected)
- [Django]-Remove the default delete action in Django admin
2👍
Setting Background Image URL – Update from 2021.
I am sure most of you are using separate .css
files for your styles.
Here is a simple explanation:
You need to set STATIC_URL = '/static/'
in your settings.py
file to tell Django where to find your static files. ALso, you might already know this since you came this far to find an answers. But here you go:
You need to include {% load static %}
in your template.
Now, you want to set background image for an element. Here is a sample static folder structure:
static
│
├───css
│ ├───accounts
│ └───homepage
│ top.css
├───img
│ top-image.png
└───js
dropdown.js
From top.css
file, you want to access img/top-image.png
file. Here are all the options you have:
/* The best option because it also works with cloud storage services like AWS*/
.my-element {
background-image: url("/static/img/top-image.png");
}
/* It works when Django is serving your static files from local server, not recommended for production*/
.my-element {
background-image: url("../../img/top-image.png");
}
The rest of the examples assume you are writing inline styles or inside <style>
tag within your template (not in a separate .css
file)
/* Because it is inside your template, Django can translate `{{STATIC_URL}}` into a proper static files path*/
.my-element {
background-image: url("{{STATIC_URL}}img/top-image.png");
}
/* Similarly you can use {% static 'static_path' %} inside your template with no issues*/
.my-element {
background-image: url("{% static 'img/top-image.png' %}");
}
Here you go – many possible ways you can access your static files from css
.
- [Django]-Django model inheritance: create sub-instance of existing instance (downcast)?
- [Django]-Unable to import path from django.urls
- [Django]-Django import error – No module named core.management
1👍
Here is the structure of directories for my project so you can be in context of why i’m using the URL’s i am using and so you can adapt it to your project.
Root directory is the folder than contains the project and apps. I have 4 apps (contacto, galeria, inicio, mapa) and the "WebCalistenia" which is the folder generated when you create a project. There i have static folder with a child called as the father ("WebCalistenia") which has two childs "/css" and "/img"
This is what worked for me.
Firstly you have to {% load static %} on your HTML.
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
...
Now you’ll link the CSS to HTML
<link rel="stylesheet" href="{% static 'app_name/css/document.css' %}">
Finally on the css file you will write:
background: url("../img/image_name.jpeg");
- [Django]-Where to put business logic in django
- [Django]-Using Basic HTTP access authentication in Django testing framework
- [Django]-How to return custom JSON in Django REST Framework
1👍
Put apostrophe in the start and ending of Django links and it should work.
background: url('{% static "img/sample.jpeg" %}') 50% 0 no-repeat fixed;
- [Django]-Django syncdb and an updated model
- [Django]-Prefetch_related for multiple Levels
- [Django]-Programmatically saving image to Django ImageField
1👍
maybe your url path is incorrect if it is correct make your .css file static and after running the server make sure you clear all the cached images and file, you can clear the cache by pressing Ctrl+Shift+Del and ticking just ‘Cached images and files’.
- [Django]-Django: How do I add arbitrary html attributes to input fields on a form?
- [Django]-Good ways to sort a queryset? – Django
- [Django]-How to change User representation in Django Admin when used as Foreign Key?
0👍
base.html in body tag
<body>
{% load static %}
</body>
style.css
#third{
background: url("/static/img/sample.jpeg") 50% 0 no-repeat fixed;
color: white;
height: 650px;
padding: 100px 0 0 0;
}
problem slove
- [Django]-Annotate a queryset with the average date difference? (django)
- [Django]-Example of Django Class-Based DeleteView
- [Django]-How to update an existing Conda environment with a .yml file
0👍
hello I had some problems I used pycharmS as tool this how I managed to solve the problem
obviously you have to load static in your html file and setup your settings.py for
if all have be done well but the issue is on css file
your image is in folder called img which is under static folder
YOU HAVE TO DO LIKE THIS :
background: Url("../img/myimage.jpeg")
; this is the part of your image
don’t put all settings code of the background on the same line
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
YOU USE BROWSER LIKE CHROME TO OPEN YOUR PROJECT I USED MICROSOFT EDGE NO CHANGE ON MY PROJECT HAS BEEN APPLIED SIMULTANEOUS
- [Django]-In django, how do I call the subcommand 'syncdb' from the initialization script?
- [Django]-Actions triggered by field change in Django
- [Django]-How to check whether the user is anonymous or not in Django?
- [Django]-How to mock users and requests in django
- [Django]-"No 'Access-Control-Allow-Origin' header is present on the requested resource" in django
- [Django]-Is "transaction.atomic" same as "transaction.commit_on_success"?
0👍
Although the solutions listed here are right I just want to add one more thing you need to clear your browser’s cache(Ctrl + F5) after updating your CSS.
Refer to this link.
- [Django]-How can one use enums as a choice field in a Django model?
- [Django]-Django Query That Get Most Recent Objects From Different Categories
- [Django]-Get user information in django templates
0👍
I got the same issue. Just make sure your image is in your CSS directory. Because since you load your CSS file in HTML with {% load static %} that mean every time the CSS file will search for the image in that directory (I was putting my image in outside of the "static directory where live my CSS file" that why it didn’t work). So to be simple put your image in the static directory (your image and CSS file in the same directory of the "static folder")
- [Django]-Django – Website Home Page
- [Django]-Django Rest Framework File Upload
- [Django]-Count() vs len() on a Django QuerySet
0👍
I had the same puzzle and I followed above mentioned answers but for some reasons, quotations didn’t work for me.
This is what worked for me in template:
{% load static %}
background-image: url('{% static 'my_folder/image.jpg' %}');"
- [Django]-Django Rest Framework: Dynamically return subset of fields
- [Django]-Django can' t load Module 'debug_toolbar': No module named 'debug_toolbar'
- [Django]-How to create table during Django tests with managed = False
0👍
here is the best solution from Django Documentation, but i post the simple solution anyway:
1- django.contrib.staticfiles should be included in your INSTALLED_APPS in
Settings.py
file.
2- add the following to the end of
settings.py
if it’s not added already.
STATIC_URL = '/static/'
3- in the html file use static to load the image either Via img tag or css.
{% load static %}
<img src="{% static 'my_app/example.jpg' %}" alt="My image">
or
{% load static %}
<style>
.bgimg {
background-image: url("{% static 'my_app/example.jpg' %}");
}
</style>
4- (IMPORTANT)
Create static folder in your app directory and then create directory inside your static folder with the name of your app again and put your image in there. the folders would be the following:
my_app/static/my_app/example.jpg
after all these steps the image should show perfectly fine.
- [Django]-How to submit form without refreshing page using Django, Ajax, jQuery?
- [Django]-HTTPError 403 (Forbidden) with Django and python-social-auth connecting to Google with OAuth2
- [Django]-Gunicorn Connection in Use: ('0.0.0.0', 5000)
0👍
Instead of adding in .css file you can use html style tag.
Add this at top of your HTML
{% load static %}
In <head>
tag add like this
<style>
#third {
background: url("{{ STATIC_URL }}img/sample.jpeg") 50% 0 no-repeat fixed;
}
</style>
It will not broke if in future you change your static file path
- [Django]-How do I make an auto increment integer field in Django?
- [Django]-Django – how to create a file and save it to a model's FileField?
- [Django]-Selecting specific fields using select_related in Django
0👍
If any of the above answers does not solve your problem try clearing your browser cache.
on windows shift + f5
- [Django]-Django-Admin: CharField as TextArea
- [Django]-Django model manager objects.create where is the documentation?
- [Django]-Access web server on VirtualBox/Vagrant machine from host browser?
0👍
Try this one
background-image: url(‘{% static "images/image.jpg" %}’);
Replace the images/image.jpg with your exact file path bearing in mind it should be in static files
- [Django]-How to read the database table name of a Model instance?
- [Django]-Django: Switching to Jinja2?
- [Django]-Django template system, calling a function inside a model
0👍
From Django’s official tutorial (version 4.2):
For the purposes of this tutorial, we’re using a file named
background.png, which will have the full path
polls/static/polls/images/background.png.Then, add a reference to your image in your stylesheet
(polls/static/polls/style.css):
body {
background: white url("images/background.png") no-repeat;
}
I’d guess that this is the currently preferred method, since they teach it that way.
- [Django]-Django: how to do calculation inside the template html page?
- [Django]-Python MySQLDB: Get the result of fetchall in a list
- [Django]-What is reverse()?
-1👍
In case there’s anyone looking for another way to solve this, you may want to hot-link the image from your server or any image hosting service you have access to. Here’s how I solved this:
- Upload the image in an image hosting site or your server (try Drive/Dropbox)
- Right click and open the image in a new tab to access the image URL
- Copy the image URL with the (.jpeg, .png) extension and paste in your HTML doc.
Here’s an example:
https://images.your-host.com/photos/image-path-here.jpeg
- [Django]-Save base64 image in django file field
- [Django]-Why there are two process when i run python manage.py runserver
- [Django]-Distributed task queues (Ex. Celery) vs crontab scripts
-3👍
If your img.jpeg
file is located within your static
directory, you should use /static/img.jpeg
. This path starts from the root directory, goes into the static
directory, and accesses the img.jpeg
file.
if your img.jpeg
file is located within the root directory, you should use /img.jpeg
. This path starts from the root directory and accesses the img.jpeg
file directly.
Remember, the path you use depends on where your img.jpeg
file is located
- [Django]-Django-Bower + Foundation 5 + SASS, How to configure?
- [Django]-Why use Django on Google App Engine?
- [Django]-Django – what is the difference between render(), render_to_response() and direct_to_template()?