How to dynamically load multiple images using JavaScript with a Django backend?

I’m developing a D3-based visualization tool that lets users interact with image paths. Currently, it functions well, but I’d like users to select a background image through a dropdown menu.

The challenge I’m facing is that JavaScript is unable to access local files due to Cross-Origin Resource Sharing (CORS) restrictions. To address this, I’ve set up a backend using Django.

Here’s the JavaScript snippet I’m working on to manage the image:

window.CHOSEN_IMAGE = "INSERT PATH HERE";

I have a functional dropdown allowing users to choose an image, and I capture the corresponding file path. However, when I attempt to load the image as follows:

window.DIAGRAM.append("image")
    .attr("width", window.CANVAS_WIDTH + "px")
    .attr("height", window.CANVAS_HEIGHT + "px")
    .attr("xlink:href", window.CHOSEN_IMAGE);

this fails, and I receive a 404 error displaying a placeholder image. I have tried two approaches:

  1. I found a solution that required hardcoding every image into an HTML file, which is not practical for me, as I need a more flexible method when users select different images later.
  2. I also attempted to reference static images using a method I came across, but logging the variable yields no results. My settings.py contains: STATIC_URL = '/static/'.

I need guidance on how to load images dynamically with JavaScript without predefining them in HTML. I suspect I might be overlooking something important.

Consider using Django’s static file handling to serve your images, so update the image src dynamically via an endpoint that manages the image path. Ensure your Django views have @csrf_exempt if doing an AJAX request. JS can update xlink:href with the URL from Django’s static files.

Have you tried using a JavaScript fetch call to grab the image paths from your Django backend? Maybe you could create an endpoint that returns a JSON response with the list of available image paths. How are you handling the state when the image is selected? Could there be a hiccup there?