1

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

itsdiy0
  • 13
  • 3
  • did you try to upload new picture is it loading? – enes islam Jun 22 '22 at 07:58
  • yes, I re-uploaded them, I uploaded new images, literally everything, nothing happened, still not loading – itsdiy0 Jun 22 '22 at 07:59
  • Did you update the `debug` value on `settings.py`? When this value is false django does not serve the media and you should give it to web servers like nginx – Dad Jun 22 '22 at 08:00
  • yes, I tried the Debug=False & True, both same situation, I even didn't change the value before this bug, It was fine when debg=True, suddenly in the True this happened – itsdiy0 Jun 22 '22 at 08:01

2 Answers2

0

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.

Damoiskii
  • 1,328
  • 1
  • 5
  • 20
-1

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.

veksor
  • 302
  • 1
  • 7