简体   繁体   中英

Django not serving media files when DEBUG is turned to False

Django is not serving my media files when DEBUG = False .

Here is my code :

DEBUG = False
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media')

I've tried several things but none have worked.
Please help me if you know the answer to my problem!

I recently had a similar issue.

In development, the Django development server serves the static files as documented in the Django docs . If settings.DEBUG is False then static file serving by the development server stops. See this Stack Overflow post: Why does DEBUG=False setting make my django Static Files Access fail?

In addition to these configuration steps, you'll also need to actually serve the static files.

During development, if you use django.contrib.staticfiles, this will be done automatically by runserver when DEBUG is set to True (see django.contrib.staticfiles.views.serve()).

This method is grossly inefficient and probably insecure, so it is unsuitable for production.

For production, there are options for serving static files as documented here.

I solved the issue of serving static files in production on an instance of Dokku —the smallest PaaS implementation you've ever seen—that is similar to Heroku.

I used a package called Whitenoise that is discussed in this blog post .

I found Whitenoise to be the easiest solution to serving static files for a small Django application without having to configure a separate static file server.

如果你想部署你的 django 项目最佳实践,请设置DEBUG=FalseALLOWED_HOSTS=['your_host']然后使用命令./manage.py collectstatic收集你的静态和媒体文件

As i can see your question is regarding media files but the answers are given about static files which are different if we see them at deployment level. For static files, you can simply use whitenoise. That will work perfectly. It will also work with media files but only when DEBUG = True and for shorter time(eg, if you deploy your app on some platform which uses dynos like heroku, dynos refresh after a particular time. In heroku it is 30 min and after that media files will be deleted no matter whether the debug is set to true or false.) Which is not secure during deployment.So to make your media files working, you need some third party support to serve your media files to your site like Amazon S3 buckets which will store your media files and will serve them to your website. Hope you got the answer!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM