mardi 15 octobre 2019

Serve django media files locally in Development environment

I use Amazon S3 to store my media files in production using boto3 package, but I don't want to create a bucket for a local development environment. So I was wondering if there is a way to serve media files locally.

My storage related settings:

if USE_S3:
    # aws settings
    AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
    AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')

    AWS_STORAGE_BUCKET_NAME = os.environ.get('BUCKET_NAME')
    AWS_S3_REGION_NAME = os.environ.get('BUCKET_REGION')
    DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

STATIC_URL = '/django_static/'
STATIC_ROOT = os.environ.get('DJANGO_STATIC_ROOT')

MEDIA_URL = '/media/'
if not USE_S3:
    MEDIA_URL = "http://localhost:8000" + MEDIA_URL
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

In urls I added this:

urlpatterns = [
    # usual urls...
]

if not settings.USE_S3:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

It turns out that static method returns empty array if its first parameter has 'http' inside, meaning that I can not use it for serving from my server.

If you have faced the same issue and solved it or you know where to look up the solution, plz let me know.

Aucun commentaire:

Enregistrer un commentaire