I'd like to use an image file as a background-image on Django
. But I do not know how. First, I read this and tried to write like following this in a css file.
#third{ background: url("img/sample.jpeg") 50% 0 no-repeat fixed; color: white; height: 650px; padding: 100px 0 0 0; }
But this does not work.
{% load staticfiles %} #third{ background: url({% static "img/sample.jpeg" %}) 50% 0 no-repeat fixed; }
and
#third{ background: url("../img/sample.jpeg") 50% 0 no-repeat fixed; }
don't work, too.
How do you usually write css file when you use background-image on css files? Would you please give me some advices?
C:\~~~~~~> dir hello\static\img 2016/09/28 19:56 2,123 logo.png 2016/09/24 14:53 104,825 sample.jpeg C:\~~~~~~> dir hello\static\css 2016/09/29 20:27 1,577 site.css C:\~~~~~~> more lemon\settings.py BASE_DIR = os.path.dirname(os.path.dirname(__file__)) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) C:\~~~~~~> more hello\templates\base.html {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static "css/site.css" %}" />
Django version: 1.9.2
Make sure you have run python manage.py collectstatic after changes or inserting CSS files. There are two static folders that need to have had the same change, one in the root and one in the main folder named after your project. Make sure you're not using background: url(../img/image.
The background-image CSS property sets one or more background images on an element.
In django we can deal with the images with the help of model field which is ImageField . In this article, we have created the app image_app in a sample project named image_upload. The very first step is to add below code in the settings.py file. MEDIA_ROOT is for server path to store files in the computer.
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
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' }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With