Django - Media in production is not working

那年仲夏 提交于 2019-12-11 14:30:08

问题


My static files are working well, but my media ones have a problem. I already deployed my website in heroku and it is online in production. (DEBUG=False) Look at the code:

settings.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = bool(os.environ.get('DJANGO_DEBUG', True))
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    # '/var/www/static/'
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = '/media/'
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
STATICFILES_STORAGE = 
'whitenoise.storage.CompressedManifestStaticFilesStorage'

urls.py

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, 
document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, 
document_root=settings.MEDIA_ROOT)

models.py

cartaz = models.FileField(default='/static/images/logo.jpg')

index.html

<img src="{{campeonato.cartaz.url}}" class="img-responsive">

My Github repository

Here is the problem, I was uploading an image in the admin section and then it worked well, but suddenly after a couple minutes the image disappeared from the website and I got the following error:

Not Found:/media/tdscampeonatos_rzFCbET.jpg

Then I added a media repository inside my project in github with the images I had uploaded:

My Github repository after I added the media

Then the images I had added to the media repository worked, but the ones I didn't added was still not working. I uploaded some more images and I got the same error, because the images was not going directly to the media path I had created in the Github repository. 5 days trying to fix this, I already looked for almost everything in internet. Please help me!


回答1:


You are deploying on heroku. Probably the hobby plan. On this plan, the app is made to sleep when not active then freshly redeployed when accessed. Thus the media files created during last run get deleted

You should upgrade your plan or consider using a thirdparty storage like cloudinary to store the media



来源:https://stackoverflow.com/questions/45591985/django-media-in-production-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!