开发者

Why can't Django find my admin media files once I leave the built-in runserver?

开发者 https://www.devze.com 2023-01-03 02:47 出处:网络
When I was using the 开发者_JAVA技巧built-in simple server, everything is OK, the admin interface is beautiful:

When I was using the 开发者_JAVA技巧built-in simple server, everything is OK, the admin interface is beautiful:

python manage.py runserver

However, when I try to serve my application using a wsgi server with django.core.handlers.wsgi.WSGIHandler, Django seems to forget where the admin media files is, and the admin page is not styled at all:

gunicorn_django

How did this happen?


When I look into the source code of Django, I find out the reason.

Somewhere in the django.core.management.commands.runserver module, a WSGIHandler object is wrapped inside an AdminMediaHandler.

According to the document, AdminMediaHandler is a

WSGI middleware that intercepts calls to the admin media directory, as defined by the ADMIN_MEDIA_PREFIX setting, and serves those images. Use this ONLY LOCALLY, for development! This hasn't been tested for security and is not super efficient.

And that's why the admin media files can only be found automatically when I was using the test server.

Now I just go ahead and set up the admin media url mapping manually :)


Django by default doesn't serve the media files since it usually is better to serve these static files on another server (for performance etc.). So, when deploying your application you have to make sure you setup another server (or virtual server) which serves the media (including the admin media). You can find the admin media in django/contrib/admin/media. You should setup your MEDIA_URL and ADMIN_MEDIA_URL so that they point to the media files. See also http://docs.djangoproject.com/en/dev/howto/static-files/#howto-static-files.


I've run into this problem too (because I do some development against gunicorn), and here's how to remove the admin-media magic and serve admin media like any other media through urls.py:

import os

import django

...

admin_media_url = settings.ADMIN_MEDIA_PREFIX.lstrip('/') + '(?P<path>.*)$'
admin_media_path = os.path.join(django.__path__[0], 'contrib', 'admin', 'media')

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^' + admin_media_url , 'django.views.static.serve', {
        'document_root': admin_media_path,
    }, name='admin-media'),
    ...
)

Also: http://djangosnippets.org/snippets/2547/

And, of course, #include <production_disclaimer.h>.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号