Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Page not found 404 Django media files

I am able to upload the files to media folder( '/peaceroot/www/media/') that I have set up in settings.py as below

MEDIA_ROOT = '/peaceroot/www/media/' MEDIA_URL = '/media/' 

But through admin I tried to access the uploaded image file

http://localhost:8000/media/items/1a39246c-4160-4cb2-a842-12a1ffd72b3b.jpg

then I am getting 404 error.

The file exists at peaceroot/www/media/items/1a39246c-4160-4cb2-a842-12a1ffd72b3b.jpg

like image 822
madhu131313 Avatar asked Mar 29 '16 09:03

madhu131313


People also ask

How do I fix 404 error in Django?

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Let's do that by turning off Django debug mode. For this, we need to update the settings.py file.

How do I add media to Django settings?

MEDIA_ROOT SettingCreate a new directory named media inside Django project root directory ( TGDB/django_project ), the same place where manage.py is located. Open settings.py file and add the following code to the end of the file, just below STATICFILES_DIRS which we had set earlier.


2 Answers

Add media url entry in your project urlpatterns:

from django.conf.urls.static import static from django.conf import settings  ... urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 
like image 154
v1k45 Avatar answered Sep 18 '22 04:09

v1k45


The better way for MEDIA_ROOT is,

try to make media path dynamic will be easy when you shift your project.

Settings.py

BASE_DIR = os.path.dirname(os.path.dirname(__file__))   MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/') MEDIA_URL = '/media/' 

urls.py

from django.conf import settings from django.conf.urls.static import static  urlpatterns = [     # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 

Look at this

https://docs.djangoproject.com/en/dev/howto/static-files/

like image 32
Kamlesh Avatar answered Sep 21 '22 04:09

Kamlesh