简体   繁体   中英

Apply background image to div in django using javascript

I am building a quiz app using django where on Q.4 I have to display an image in the django template using javascript. I tried this in my .js file but didn't succeed:

document.getElementById("img").style.backgroundImage="url('images/image_name.jpg')";

Here images is the subdirectory in static directory. The error I am getting is:

Not Found: /quiz/images/image_name.jpg

Here is my main urls.py :

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('quiz/',include('blogsite.urls')),
    path('admin/', admin.site.urls),
]

If images is a subdirectory of static , why would you use 'images/image_name.jpg' .

This would just add the path images to the current path.

You have to declare the absolute path:

url('/static/images/image_name.jpg')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM