Django Admin : Class Media

2019-04-29 22:37发布

I have a class Media as follows

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

The staticfiles app prepends STATIC_URL to the media path. But I want MEDIA_URL to be prepended instead of STATIC_URL and STATIC_URL isn't empty. How can this be done?

1条回答
孤傲高冷的网名
2楼-- · 2019-04-29 22:55

You can achieve that with the following settings:

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)

Using MEDIA_URL is not advised for serving static files. According to django documentation, MEDIA_URL will not be referred for media files, when STATIC_URL is not empty. Refer to this part of documentation.

So I recommend you to use the following settings:

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)
查看更多
登录 后发表回答