0

I tried following this or this or this but nothing works for me - I have a directory called media which has uploaded files in it - but I cannot access it with http://127.0.0.1:8000/media/ - Page not found (404).

My settings.py:

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'PROJECT/static'),
]

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

and my urls.py:

from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from django.views.generic.base import RedirectView, 
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('home/', RedirectView.as_view(url='/')),
    path('admin/', admin.site.urls),
    path('', include('appname.urls')),
    path('', include('django.contrib.auth.urls')),
    path(r'^login', auth_views.LoginView.as_view(template_name='registration/login.html')),
]

if settings.DEBUG is True:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Bonus question because I could not try it until now: How would I access an image with filename.jpg in /media/ in a template?

I fixed the issue with trial and error:

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'projectname/static'),
]

MEDIA_ROOT = os.path.join(BASE_DIR, "projectname", "media")
MEDIA_URL = "/media/"
xtlc
  • 1,070
  • 1
  • 15
  • 41
  • in settings.PY, is DEBUG set to true? – plum 0 Dec 28 '20 at 14:20
  • Seems you are doing all right. Except: Are you trying to reach http://127.0.0.1:8000/media/ with some file in the end(http://127.0.0.1:8000/media/filname.png)? or just like you showed in question? if it is like in question(http://127.0.0.1:8000/media/), it will give you 404 because there is no file as ""empty string. – Marat Ablayev Dec 28 '20 at 14:40
  • yes, debug is set to `true`. – xtlc Dec 28 '20 at 15:49
  • When I try to go to `http://127.0.0.1:8000/media/test.bmp` I still get a 404 (the file is in the folder `media`). – xtlc Dec 28 '20 at 15:50
  • Interesting though - `print(MEDIA_ROOT`) results in `C:\Users...\projectname\media/` - see last slash. Omitting it does not help though. – xtlc Dec 28 '20 at 15:54

1 Answers1

0

try it worked

your_app urls.py

from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
   ....
]
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

settings.py

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, "media")
)