Loading/Refreshing HTML Components through Javascript in Django

I’m trying to load an image from the static folder in my django project on button click. This needs to happen from my button click function but the image is not being rendered.

On button click, I’m unable to use the src="{% static 'images/example.jpg' %}" since {% load static %} does not work in the client side from javascript functions. May I please know if there is a workaround or a way to dynamically load images from the static/images folder on a button click without refreshing my entire page?

You’ve got a couple different options for this:

  • If you’re using a button to activate this, you could render that static reference as a data attribute in the button, and access it from the JavaScript event handler.

  • You could render that reference as a data element on the page using the json_script tag

  • You could include the reference to the image on your page in a hidden div, and have your button just reveal the image when necessary.

There probably are some other options, but these are the ones that come to mind off the top of my head.

1 Like

Thanks for the answer @KenWhitesell