Home > Software design >  Django medias(pictures) suddenly not loading
Django medias(pictures) suddenly not loading

Time:06-22

I am developing a website with Django, I had a lot of pictures in my project, uploaded from the admin panel and saved in the Media folder which I created for these uploads separately, It was working fine and exact way I wanted in months, Suddenly they are just not loading, getting 404 for all of them, without any change in project, they are just not loading. My media path in Settings.py :

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

I have added this to the end of my urls.py of the app:

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

and as i said, it was working fine for a long, suddenly this happened

edit: I just figured it out that this is happening when I am using redirect function in one of my views

CodePudding user response:

Another way to do it is:

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
     path('admin/', admin.site.urls),
     # other URLs ... 
]

# If DEBUG=True in the settings file
if settings.DEBUG:
     urlpatterns  = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

So we're adding static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to the urlpatterns if DEBUG=True in the settings.py file. This gives a better management in some sense.

CodePudding user response:

I had the same issue and this helps me :

Add this in your urls.py in the urlpatterns list :

from django.views.static import serve
from django.conf import settings
from django.conf.urls import url
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
# YOUR URLS ARE HERE
]

Of course stay in Debug=True in settings.py.

  • Related