Django - 从 javascript 访问 admin_media_prefix
在管理中,我希望可以通过任何 javascript 访问管理媒体网址。
我已经将其包含在请求上下文中。
但是为了能够从包含的 javascript 访问它,
<script type="text/javascript">
window.__admin_media_prefix__ = "{{ ADMIN_MEDIA_URL }}";
</script>
我是否必须将类似的内容放入基本模板中,或者是否有更简洁的方法来做到这一点?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
django 不会以任何方式解释媒体(静态)文件。在生产站点上,Python 代码甚至可能无法访问这些文件,因为它们可能由前端 Web 服务器提供服务。所以你有一个疯狂的选择:使用服务器端包含(SSI)之类的东西,通过某种方式解析配置文件,将变量内容嵌入到选择的媒体文件中。
更好的想法是为每个站点使用相同的管理媒体前缀方案,为您选择的网络服务器提供灵活的每个站点配置文件,其中管理媒体文件将从某个已知位置提供服务:
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:
我可以提供一个有点“邪恶”的解决方案:因为 Django 1.4 django.contrib.admin 正在使用 django.contrib.staticfiles 来处理所有静态内容。由于管理员的 Javascript 使用
missing-admin-media-prefix
(如果未找到),我们可以进行重定向,例如在 Apache 中:(如果您的
STATIC_URL
设置为/static
,当然)如果您经常在 Admin 中进行修改,并且不想用全局 Javascript 变量声明来扰乱您的模板,那么此方法特别好。
I can provide a somewhat "evil" solution: since Django 1.4
django.contrib.admin
is usingdjango.contrib.staticfiles
for everything static. Since Admin's Javascript is usingmissing-admin-media-prefix
if it's not found, we can do a redirect, e.g. in Apache:(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.