0

My media which i have uploaded using the form in this question View does not seem to be saving all the information in my model is being uploaded to the correct /media/images folder that i have defined. However, on access it returns a 404. i have tried to follow the instructions on https://stackoverflow.com/a/39359264 but still am getting a 404.

my template code

{% for books in object_list %}
    <img src="{{ books.cover_pic.url }}">
{% endfor %}

settings.py

STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

my urls.py

urlpatterns =[
    path('', views.index, name='index'),
] 
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

my model code for the image is

cover_pic = models.FileField(null=True, blank=True, upload_to='images/')

my media folder is at base dir (next to manage.py). What am i overlooking?

falsafa
  • 15
  • 6

1 Answers1

0

Try this. It works for me this way. You also try some method that I commented in the models.py incase of anything.

settings.py

import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

MEDIA_ROOT = (
BASE_DIR
)


MEDIA_URL = '/media/'

models.py ...

#Here you can try changing FileField to ImageField if you like.
# You can also try directory uploads as image without backslash
#cover_pic = models.ImageField(upload_to='images')

cover_pic = models.FileField(upload_to='images/')

urls.py(project's)

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

template (.html)

  {% for books in object_list %}
    <img src="{{ books.cover_pic.url }}">
{% endfor %}
Nancy Moore
  • 2,322
  • 2
  • 21
  • 38
  • The error was in putting the static settings url in the app urls.py and not the project wide urls.py. Thank you. It works now. – falsafa Mar 30 '19 at 04:46