Profile

Способ использования background-image в css файлах с Django

Я хотел бы использовать файл изображения в качестве фонового изображения на Django , Но я не знаю как. Во-первых, я прочитал это и попытался написать, как после этого в файле CSS.

 #third< background: url() 50% 0 no-repeat fixed; > 

Как вы обычно пишете файл CSS, когда вы используете background-image в файлах CSS? Не могли бы вы дать мне несколько советов?

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 " /> 

18 ответов

Скорее всего, это будет работать. Используйте «/static/» перед вашим изображением, а затем попробуйте их. Спасибо

Удостоверься что django.contrib.staticfiles включен в ваш INSTALLED_APPS.

В вашем файле settings.py определите STATIC_URL: STATIC_URL = ‘/static/’

По некоторым причинам, которые я не могу объяснить, принятый ответ не сработал для меня. (Я хотел использовать картинку в качестве обложки для всего тела).

Тем не менее, вот альтернатива, которая сработала для меня для любого, кто может быть полезен для кого-то, кто встретит.

В файле CSS, который находится в каталоге статических файлов, я написал следующее:

Читайте также:  Цветовая гамма в php

Вы не должны включать *»* в вашем файле CSS.

  1. включают на вершине
  2. создайте ссылку на стиль, как показано ниже. ‘ rel=’stylesheet’ type=’text/css’>

Настройка URL фонового изображения — обновление с 2021 года.

Я уверен, что большинство из вас использует отдельные файлы для своих стилей. Вот простое объяснение:

Вам нужно установить STATIC_URL = ‘/static/’ в вашей settings.py file, чтобы сообщить Django, где найти ваши статические файлы. Кроме того, вы, возможно, уже знаете это, так как зашли так далеко, чтобы найти ответы. Но вот, пожалуйста:

Вам нужно включить в вашем шаблоне.

Теперь вы хотите установить фоновое изображение для элемента. Вот пример статической структуры папок:

static │ ├───css │ ├───accounts │ └───homepage │ top.css ├───img │ top-image.png └───js dropdown.js 

Из top.css файл, к которому вы хотите получить доступ img/top-image.png файл. Вот все возможные варианты:

 /* 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"); >

В остальных примерах предполагается, что вы пишете встроенные стили или внутри в вашем шаблоне (не в отдельном .css файл)

 /* Because it is inside your template, Django can translate `>` into a proper static files path*/ .my-element < background-image: url(">img/top-image.png"); > 
 /* Similarly you can use inside your template with no issues*/ .my-element < background-image: url(""); > 

Вот и все — множество возможных способов доступа к статическим файлам из css .

Источник

Writing your first Django app, part 6¶

This tutorial begins where Tutorial 5 left off. We’ve built a tested web-poll application, and we’ll now add a stylesheet and an image.

Aside from the HTML generated by the server, web applications generally need to serve additional files — such as images, JavaScript, or CSS — necessary to render the complete web page. In Django, we refer to these files as “static files”.

For small projects, this isn’t a big deal, because you can keep the static files somewhere your web server can find it. However, in bigger projects – especially those comprised of multiple apps – dealing with the multiple sets of static files provided by each application starts to get tricky.

That’s what django.contrib.staticfiles is for: it collects static files from each of your applications (and any other places you specify) into a single location that can easily be served in production.

If you’re having trouble going through this tutorial, please head over to the Getting Help section of the FAQ.

Customize your app’s look and feel¶

First, create a directory called static in your polls directory. Django will look for static files there, similarly to how Django finds templates inside polls/templates/ .

Django’s STATICFILES_FINDERS setting contains a list of finders that know how to discover static files from various sources. One of the defaults is AppDirectoriesFinder which looks for a “static” subdirectory in each of the INSTALLED_APPS , like the one in polls we just created. The admin site uses the same directory structure for its static files.

Within the static directory you have just created, create another directory called polls and within that create a file called style.css . In other words, your stylesheet should be at polls/static/polls/style.css . Because of how the AppDirectoriesFinder staticfile finder works, you can refer to this static file in Django as polls/style.css , similar to how you reference the path for templates.

Just like templates, we might be able to get away with putting our static files directly in polls/static (rather than creating another polls subdirectory), but it would actually be a bad idea. Django will choose the first static file it finds whose name matches, and if you had a static file with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the best way to ensure this is by namespacing them. That is, by putting those static files inside another directory named for the application itself.

Put the following code in that stylesheet ( polls/static/polls/style.css ):

Источник

фоновое изображение в стиле css из статических файлов с django

Я использовал этот шаблон для создания домашней страницы в проекте django, однако я не могу правильно отобразить фоновое изображение (bg.jpg) Фоновое изображение используется как foollows в файле css:

и пробовал все решения, но не из них, похоже, работает.

Мое дерево проекта похоже

project_name - home - static --home ---style.css --images ---bg.jpg - templates -- home ---base.html ---home_template.html 

в файле style.css я попробовал следующее

background-image: url(/media/usr/path_to_project/project_name/home/static/images/bg.jpg); background-image: url("/media/usr/path_to_project/project_name/home/static/images/bg.jpg"); background-image: url(../images/bg.jpg); background-image: url("../images/bg.jpg"); background-image: url("); 

в моем шаблоне base.html у меня есть:

и в моем home_template.html у меня есть

   

Nam vel ante sit amet libero scelerisque facilisis eleifend vitae urna

Morbi maximus justo

Странно то, что у меня есть другие изображения в моей директории static/images, которые отображаются в шаблоне с помощью встроенного стиля, например:

возможно, ваше изображение повреждено, или что-то подобное случилось со мной раньше, и проблема была в том, что изображение было .JPG в заглавных .JPG . попробуйте открыть IMG из URL-адреса напрямую, чтобы узнать, если это проблема CSS или нет?

@Veehmot Вот и все, спасибо. Он работает как встроенный стиль, а также в файле CSS. Можете ли вы опубликовать свой комментарий в качестве ответа, чтобы я мог проверить его?

Источник

Css django background image with static code example

My CSS file was in CSS folder and images were in the images folder. Solution 2: Try this settings.py urly.py your css and jquery on template If your are using production version try this Hope this will help you Don’t forget to attached in your INSTALLED_APPS Solution 1: Using a background image in CSS file doesn’t require a static block.

Setting static background image in local Django environment

Your css file is not rendered by Django template engine and so > is not being replaced. You’ll have to use /static/img/IMG_0002.jpg in the CSS file or move that bit of CSS in your html file’s style tag.

if settings.DEBUG: urlpatterns += patterns('django.views.static', (r'^static_media/(?P.*)$', 'serve', < 'document_root': '/path/to/static_media', 'show_indexes': True >),) 

your css and jquery on template

>base_min.css" type="text/css" media="screen"> 

If your are using production version try this

MEDIA_URL = 'http://media.example.org/' Development: /static_media/base_min.css Production: http://media.example.org/base_min.css 

Don’t forget to attached ‘django.contrib.staticfiles’, in your INSTALLED_APPS

The way to use background-image in css files with Django, 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 … Code samplebackground: url(«/static/img/sample.jpeg») 50% 0 no-repeat fixed;color: white;height: 650px;padding: 100px 0 0 0;>Feedback

How to load background image from style.css in django framework

Using a background image in CSS file doesn’t require a static block. Just make sure you have path correctly matched with your folders. Use ./ to go back in path mapping.

css/base.css images/slide1Back.png 

My CSS file was in CSS folder and images were in the images folder. So I used this.

background-image: url('./images/slide1Back.png'); 

First of all, make sure you added this line to your html file:

then put this to your settings.py:

STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) 

now everythings work like what!

      ">  
A unique cloud hosting provider

Our efforts and focus are always directed to our clients and their needs

#subheader.about < background: url("../images/s8.jpg") center center no-repeat; padding: 100px 25px; >#subheader.about:after

please attention, i used ../ instead of ./

and this is result: result view

Am using this template here as about.html

A unique cloud hosting provider

Our efforts and focus are always directed to our clients and their needs

WHAT ARE WE ALL ABOUT?

Profile

Maelezo mazuri huwajenga wengine kutanikoni. (Ro 14:19) Pia, yanawanufaisha wale wanaotoa maelezo. (Met 15:23, 28) Kwa hiyo, tunapaswa kujitahidi kutoa maelezo angalau mara moja kila mkutano. Bila shaka, hatutachaguliwa kutoa maelezo kila wakati tunapoinua mkono. Kwa hiyo, ni muhimu kutayarisha majibu kadhaa..

CHOOSE

SCALE

LAUNCH

USE

 ======================== */ #subheader.about #subheader.about:after

Can tell where is the mistake or am missing something here here is the path to image projects/djangoprojects/static/images/s8.jpg

Html — Django css background-image, Django css background-image. Ask Question Asked 5 years, I try change in css background-image: url( «<% static 'img/bg.jpg' %>«); to background-image: url( «img/bg.jpg»); but don’t work it but I wanted to share this with someone trying to dynamically load a background image. My example is rendering a database …

Django: Rendering AWS S3 static files through css background-image

url('../../static/main/img/search4.jpg') 

The reason for this is your site is hosted on a domain different from your s3 bucket domain so the browser is unable to resolve the relative url

For example, if your website is at example.com the browser attempts to pop off the last 2 path components(parts of the url following a forward slash e.g /component1/component2/) so it just does nothing. You can place the relative path in your css file since it’s hosted on the same domain as your image

Setting static background image in local Django, and then put this line in the CSS file. body < font:16px/26px Helvetica, Helvetica Neue, Arial; background-image: url (" < < STATIC_URL >>img/IMG_0002.jpg»); > I know the static files bit is working because the CSS is loaded. And I can change the background color by using background-color: blue. …

Background image in django template

How to load background image from style.css in django, can you check the pictures and the code snippet added below.I have my folder arranged static/images and static/css/style.css for the css however all other images and css are loading except for the background images Using a background image in CSS file doesn’t require a static block. background …

Источник

Оцените статью