Pierre de LESPINAY
Pierre de LESPINAY

Reputation: 46178

Django - admin_media_prefix access from javascript

In the admin, I would like the admin media url to be accessible from any javascript.
I already have it included in the request context.
But in order to be able to access it from an included javascript,

<script type="text/javascript">
  window.__admin_media_prefix__ = "{{ ADMIN_MEDIA_URL }}";
</script>

Do I have to put something like that in a base template or is there a cleaner way to do that ?

Upvotes: 1

Views: 672

Answers (2)

Nikolai Prokoschenko
Nikolai Prokoschenko

Reputation: 8755

I can provide a somewhat "evil" solution: since Django 1.4 django.contrib.admin is using django.contrib.staticfiles for everything static. Since Admin's Javascript is using missing-admin-media-prefix if it's not found, we can do a redirect, e.g. in Apache:

RewriteRule ^/missing-admin-media-prefix/(.*)$ /static/admin/$1 [L,R=301]

(if your STATIC_URL is set to /static, of course)

This method is especially nice if you hack around stuff in Admin a lot and also don't want to clutter your templates with global Javascript variable declarations.

Upvotes: 1

mike_k
mike_k

Reputation: 1841

Media (static) files are not interpreted by django in any way. On a production site python code might not even have an access to that files, as they are probably served by the frontend webserever. So you have a crazy option: use something like server side includes (SSI) to embed the variable content into choosen media files by somehow parsing the config file.

Better idea would be to have same admin media prefix scheme for every site, flexible per-site config file for your webserver of choice, where admin media files would be served from some known location:

location ^~ /media/ {
    root        /.../django-$django_ver/contrib/admin/;
}

Upvotes: 2

Related Questions