How does Django serve media files?

前端 未结 5 491
谎友^
谎友^ 2021-01-02 05:01

I have set up a Django application that uses images. I think I have set up the media settings MEDIA_ROOT and MEDIA_URL correctly. However the images don\'t show up. Do you k

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-02 05:14

    FOR DEVELOPMENT ONLY

    You can setup a static media server for use with their development server by doing this in your urls.py file. I have attached the code showing how I use it (along with the forced DEBUG conditionals.)

    from django.conf import settings
    from django.conf.urls.defaults import *      
    
    # Uncomment the next two lines to enable the admin:
    from django.contrib import admin
    admin.autodiscover()
    
    urlpatterns = patterns('', 
        (r'^$', 'views.index'),            
    
        # Accounts
        (r'^accounts/login/$', 'views.user_login'),
        (r'^accounts/logout/$', 'views.user_logout'),
    
        # Contrib Modules
        (r'^admin/(.*)', admin.site.root),
    )
    
    if settings.DEBUG :
        urlpatterns += patterns('',
            (r'^media/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
        )
    

    I place my MEDIA_ROOT in a subdirectory of html/media and link to it as such in settings.py

    MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'html/media/').replace('\\','/')
    

    After development is finished, the project gets deployed to the web server where static media files are then served by Apache using directives.

提交回复
热议问题