0

I am trying to make an app where I can upload images through the Admin side, localhost:8000/admin/example but when I upload an image it gives me a 404 error when I go to the image URL.

I am new to Django and python so I am trying to learn about both of them.

Here is what I have for models, URLs, and settings

models.py

item_image = models.ImageField(upload_to = "static/images/products" )

urls.py

from django.conf.urls.static import static
from django.conf import settings

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('<int:item_id>/', views.detail, name='detail'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
MEDIA_ROOT = PROJECT_ROOT + '/static/images/products/'
MEDIA_URL = '/media/'

html file

<img src={{item.item_image.url}}>
arajshree
  • 626
  • 4
  • 13
gitBritt
  • 3
  • 5
  • can you please add the error message to the question? – Lunik Jun 27 '19 at 21:18
  • screen shot of the error message : [https://imgur.com/VofsMTN](https://imgur.com/VofsMTN) – gitBritt Jun 28 '19 at 12:50
  • The problem might be with your urls.py. I tried to replicate the problem and found that you are trying to add static files path in your django app's urls.py file. So, you should add the app's name before /media in the url, for example, /example/media/static/images/products/image_name.jpg. If you want to access the images from /media, you should add "static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)" in urls.py of the django 'project' not app. – Lunik Jun 28 '19 at 13:32

1 Answers1

0

I hope you followed the official tutorial. I assume that you have a django project named "mysite" with an app named "example".

You should add "static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)" to the urlpatterns in the urls.py file of the django project "mysite", if you want to access the images with /media.

If you decide to add it to the urls.py file of the django app "example", (which I assume is what you have done), you should be accessing the images with /example/media prefix.

Lunik
  • 300
  • 1
  • 12