Access MEDIA_URL from static Javascript files in Django

This is an old trick, that’s been very handy :) .

Many times for various reasons you’ll need to access your media files from your Javascript files, to display images, change paths, or whatever. And in most cases your development MEDIA_URL and production MEDIA_URL will be different, so having to change them depending on the enviroment can be a bit tricky being them static files I’m assuming you are using static files your your .js right?.

What I do to help this is add the following to my base.html :

<script type="text/javascript">
    var MEDIA_URL = "{{MEDIA_URL}}";
</script>

before I load any of my .js files, and in them I simply refer to the MEDIA_URL variable just as in my Django templates.

Of course, you need to have your settings.MEDIA_URL variable on template context via whatever method you feel mor confortable with, personally I use context_processors :) .

This entry was posted in django, en, geek, programacion, web and tagged , , . Bookmark the permalink.
  • http://devlog.waltercruz.com Walter Cruz

    Hi. In a post here (http://www.fairviewcomputing.com/blog/2008/04/16/django-geography-hacks/) you talk about a geo plugabble app. Have you done that?

  • http://isgeek.net/ Jj

    Hi Walter,
    No I couldnt quite finish the project. I do have the models, some forms and some views that were in my plan but not quite what I had in mind.

    Contact me if you’re interested, I could send you the code and probably we could work together

  • http://jj.isgeek.net/2009/08/23/generating-javascript-widgets-with-reversed-url-endpoints-in-django/ Jj’s blog » Generating Javascript Widgets with reversed URL endpoints in Django

    [...] is similar to this solution on accessing MEDIA_URL in Javascript files. Posted in django, en, geek, javascript, [...]

  • Abhas

    this however does not work if within the tags i include a declaration for the jquery lib

    src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”
    On doing this I get an error MEDIA_URL is undefined inspite of the declaration.I would appreciate any help on the matter.