djangodjango-modelsdjango-templatesdjango-viewsdjango-media

Setting multiple MEDIA_URL & MEDIA_ROOT in django


I've set Static and Media root as well as url's in my django app, as follows:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")

MEDIA_URL = '/crl/'
MEDIA_ROOT  = os.path.join(BASE_DIR, 'config/crl/')

It is working great, but I want to add another MEDIA_URL & MEDIA_ROOT to serve files from the /certs/ directory as follows:

NEW_MEDIA_URL = '/certs/'
NEW_MEDIA_ROOT  = os.path.join(BASE_DIR, 'config/certs/')

Is there any way to do it? I'm using Django 2.0.6 and Python 3.5


Solution

  • Multiple static URLs and static roots can be added to Django using the following steps.

    1. Configure a BASE_DIR
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    
    
    1. Create as many static roots and static URLs as you need
    STATIC_URL = '/static/'
    STATIC_ROOT = os.path.join(BASE_DIR, "static/")
    # the "static/" above is a directory inside the Django Project Directory
    
    STATIC_URL_1 = '/static-1/'
    STATIC_ROOT_1 = os.path.join(BASE_DIR, "static_1/")
    
    1. Similarly, you can create as many media roots and media URLs as you need
    MEDIA_URL = '/crl/'
    MEDIA_ROOT  = os.path.join(BASE_DIR, 'config/crl/')
    
    MEDIA_URL_1 = '/crl-1/'
    MEDIA_ROOT_1  = os.path.join(BASE_DIR, 'config/crl_1/')