Django Admin:Class Media

时间:2013-02-26 09:58:24

标签: django django-admin

我有一个类媒体如下

class helloAdmin(admin.ModelAdmin):
    class Media:
        js = ['choice.js']
admin.site.register(hello,helloAdmin)

staticfiles应用程序将STATIC_URL添加到媒体路径。但我希望MEDIA_URL代替STATIC_URL,而STATIC_URL不是空的。怎么办呢?

1 个答案:

答案 0 :(得分:5)

您可以使用以下设置实现此目的:

import os
CURRENT_PATH = os.path.abspath((os.path.dirname(__file__)))

MEDIA_ROOT = os.path.join(CURRENT_PATH, 'uploads')

MEDIA_URL = '/site_media/'

urls.py

from django.conf import settings
urlpatterns += patterns('',
    url(r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)

admin.py

class helloAdmin(admin.ModelAdmin):
    class Media:
        js = ['/site_media/choice.js']
admin.site.register(hello,helloAdmin)

建议不要使用MEDIA_URL来提供静态文件。根据django文档,当MEDIA_URL 不为空时,STATIC_URL将不会引用媒体文件。请参阅this part of documentation

所以我建议你使用以下设置:

STATIC_ROOT = 'static/'

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(CURRENT_PATH, 'media'),
)

admin.py

class helloAdmin(admin.ModelAdmin):
    class Media:
        js = ['choice.js']
admin.site.register(hello,helloAdmin)