[Fixed]-Change the background-image dynamically using MEDIA_URL and jquery

1👍

Django can’t parse template tags placed in static files, so you can’t just put {{ MEDIA_URL }} here and expect it to work fine.

But you can use it in main template and save it as a variable:

<script>media_url = '{{ MEDIA_URL }}';</script>

And then use that variable in your javascript:

url = media_url + url;

0👍

If you’re making an AJAX call to upload your file into server, best thing you can do is to pass in response for that upload full URL of uploaded file.

Glueing MEDIA_URL with path to file isn’t recommended one. You can have different media handlers that will upload files into different locations. That can break your links.

Also: if you’re trying to upload file with name that already exists on server, actual file name will be unpredictable (django will add some random characters to it)

So for best compatibility, return URL to file from your upload view, and use that in your Javascript.

Leave a comment