In Django, how can I handle static content in a CSS file?

For example, I can upload images as follows:

background: url("/path/to/image.png") 

However, since CSS files do not run through the template system, I don’t have access to regular

 {% load staticfiles %} 

What is the right way to handle such static content?

+4
source share
1 answer

The browser already knows the path to the css file, so instead use only relative URLs:

 background: url("../img/image.png") 

[EDIT]

But what happens if I have a page in / onelevel. And another page on the / really / deep / nested / page will not break the relative system? Also, if I ultimately decide to host the static content externally, I would like the research content management to be as dry as possible - OP.

Let me explain. To read a CSS file, the browser must first download it. To download it, the URL of the CSS file must be known. Thus, the browser already knows the path to the CSS file. Suppose you host your media on a CDN, and the URL is:

 http://cdn.yoursite.com/css/style.css 

When you use a relative URL like ../img/logo.png , the browser will go to the CSS file ( http://cdn.yoursite.com/css/ ) and add ../img/logo.png to it.

It works well, shorter than the whole path, and allows you to reuse the media in other projects / applications without changing the point. You can’t get any more DRY.

That is why you do not need settings.STATIC_URL anywhere next to your CSS files, it will be obtained from the file URL during HTTP maintenance.

+4
source

Source: https://habr.com/ru/post/1486341/


All Articles