asdfkjasdfjk
asdfkjasdfjk

Reputation: 3894

Django look css images into wrong directory

I have following settings for static files

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static_my_proj'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn', 'static_root')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static_cdn', 'media_root')

In the css file I do this

#mydiv{
    background-image:  url('/img/myimg.png');
}

And my directory structure

project root
 - static_my_proj
  - css
  - img
  - js

I can see from network tab that it looks for the image in static/css/img/myimg.png. However, if I do this then it works. How can I make it without using ../ at the beginning?

#mydiv{
    background-image:  url('../img/myimg.png');
}

Upvotes: 1

Views: 106

Answers (1)

Myzel394
Myzel394

Reputation: 1317

You better use {% static 'img/myimg.png %}. Hardcoded paths aren't good, because if you change your static folder, you would have to change all your code. You can't use static in your css files, but in your templates. Your code would look like this:

yourHTML.html:

{% load staticfiles %}

<div id="mydiv" style="background-image: url({% static 'img/myimg.png' %})">

</div>

Upvotes: 1

Related Questions