0

I am trying to change the background image of the div dynamically whenever the user uploads the image via ajax.

First I am passing the url of the image through ajax from the view to the template. And then I am changing the url for the css to get the image:

url = 'http://sitename.com/media/' + url;
block.css({
    'background-image': 'url('+url+')',
    'background-color': ''
});

Now the url becomes like this and this is working as expected:

url = http://sitename.com/media/uploaded_files/thomas.jpg

But when I try to use the {{MEDIA_URL}} as its describe to use in the django template

url = '{{MEDIA_URL}}' + url;

I get a 404 error and the url is changed like this:

GET http://sitename.com/page-modify/67/%7B%7BMEDIA_URL%7D%7Duploaded_files/1449049938_08_images.jpg 404 (NOT FOUND)

How can I use the {{MEDIA_URL}} from the django settings in my template to change the background-image using jquery?

2
  • Where you're putting that {{ MEDIA_URL }}? In which file? Commented Dec 2, 2015 at 10:18
  • @GwynBleidD In the js file Commented Dec 2, 2015 at 10:20

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Could you please add both your answers together, it will be much more helpful for other users too. And thank you, its working now.
Those are separate, alternative solutions. They're shouldn't be joined as one answer.
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.

1 Comment

How do I get the url of the file? I thought the field of the image was enough.

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.