Puto Miké
Puto Miké

Reputation: 73

media files stores files in MEDIA_ROOT, but serves them from app folder

I'm having trouble bending the media_root to my will.

When I try to serve an image, a suffix is appended to the file path, more precisely, it tries to point to an app (yoga) even though I want it to point to BASE_DIR / media.

For example it will give me this:

http://localhost:8000/yoga/media/images/satori.jpg

But the media folder is (auto-generated) one folder up from that in the dir hierarchy.

I've been wracking my brain, because I just can't see where that "yoga/" line is appended to the path, and I don't understand why or how it got there, lest of course we consider, that the model that it stems from lives inside the yoga app directory.

Here's what I think might be relevant. Please let me know if you want to see more of the goods.

Tree:

  .
  ├── boofers.txt 
  ├── db.sqlite3 
  ├── dos_env
  ├── manage.py
  ├── media
  ├── static
  ├── yoga
  └── yoga_dos

In settings.py:

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

in the model @ yoga/models.py:

ex_img = models.ImageField(upload_to='media/images', blank=True, default='yogapose.jpg')

in the main urls.py:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('yoga/', include('yoga.urls')),
]

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

...and in yoga/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.mk_json, name='yoga')

]

Upvotes: 2

Views: 899

Answers (1)

Manoj Tolagekar
Manoj Tolagekar

Reputation: 1970

You are getting this:

http://localhost:8000/yoga/media/images/satori.jpg

Because, you are added this way in models.py:

upload_to='media/images', 

To solve this, just add following way:

upload_to='images/'

Output look like this after adding above code:

http://localhost:8000/media/images/satori.jpg

Note: Don't create media folder inside your project or app. It will create media folder automatically inside your project.

Upvotes: 0

Related Questions