1

I am trying to add upload image to admin form in my Django project I found on GitHub. I can upload image to folder my_app(catalog)/media/images/image.png but when I try to call it in the template I can only see that image icon that appears when there is no picture.

settings.py

STATIC_URL = '/static/'

MEDIA_URL = '/media/'

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

model.py

class Book(models.Model):
    image = models.ImageField(blank=True, null = True, upload_to='images')

book_detail.html

img src="{{ book.image.url}}" width="250"

views.py

class BookDetailView(generic.DetailView):
    model = Book

urls.py

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

urlpatterns = [
    path('', views.index, name='index'),
    path('book/create/', views.BookCreate.as_view(), name='book_create'),
    path('books/', views.BookListView.as_view(), name='books'),
    path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'),

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

This is how it looks like (I print {{ book.image }} next to the picture (images/screenshot_4.png):

enter image description here

This is the error I get:

enter image description here

Amir Shabani
  • 3,857
  • 6
  • 30
  • 67
ziggy
  • 11
  • 1

2 Answers2

0

You may have dropped a ']' at the end of your urlpatterns or maybe I am mistaken

Mfon
  • 1
0

Ok I found out after spending way to much time on it. img src="{{ book.image.url}}" width="250" line in template should look like img src="../media/{{ book.image.url}}" width="250".

Hope this helps someone with the same problem.

ziggy
  • 11
  • 1