0

I want to write Django code into CSS style tag in HTML elements in order to get images from static directory. here is my original code

<a href="single.html" class="img" style="background-image: url(images/image_1.jpg);"></a>

i tried with the below code

<a href="single.html" class="img" style="background-image: {% static 'images/image_1.jpg' %};"></a>

but this isn't worked for me, how can i solve this problem? NB: i used {% load static %} to load all static files, css and js works fine but i became failed to do this.

3 Answers 3

1

First Add These Code In Your settings.py

STATIC_URL = '/static/'

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

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'myproject/static')
]


# Media settings
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Then Add These Code In Your project urls.py

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Then add this line to your html

style="background-image: url({%static 'images/person_1.jpg' %});"
Sign up to request clarification or add additional context in comments.

Comments

1

You can check if in your root project/settings.py has something like this:

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

and then, in your root project/urls.py:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [...] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

To be sure, make sure you restart your server after these changes.

Comments

0

In settings.py add this

STATIC_URL = 'static/'
STATICFILES_DIRS = [
   os.path.join(BASE_DIR, 'static')
]

try to convert style tags in this manner

style ="background-image:url(images/image_1.jpg)"

TO

style ="background-image:url('/static/images/image_1.jpg')"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.