Home > Mobile >  Django - Accessing static/media files always from a remote MEDIA_URL instead of local one during dev
Django - Accessing static/media files always from a remote MEDIA_URL instead of local one during dev

Time:06-25

I have a Django app running on a server and I would like to continue working on it locally with the runserver command. My problem concern the use of common static and media files. The media folder content changing frequently in production I have to download those media files from the server each time I want to dev locally and add those to the MEDIA_ROOT path on my computer.

The database is common to both dev and production environment since it is a MySQL host on my server.

How can I tell Django in local mode to lookup static and media files on a remote url from my domain name instead of localhost? Like https://example.com/media/ instead of : https://127.0.0.1:8000/media/

CodePudding user response:

You simply test in after main url

if settings.DEBUG:
    urlpatterns  = static(settings.STATIC_URL,
                  document_root=settings.STATIC_ROOT)
else:
   Production
  

CodePudding user response:

I don't really understand why static files have to be treated the same - they are supposed to be a part of your project sources. So local storage should have a higher priority.

But serving any of such files is still just URL dispatching, so instead of this:

urlpatterns  = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

you might try something like this:

urlpatterns  = [
    path(settings.MEDIA_URL   "<path:file_path>", RedirectView.as_view(url="https://example.com/media/%(file_path)"))
]

(did not test it)

RedirectView docs almost similar question

  • Related