0

I have looked this questions from the stack overflow. question 1 question 2 about showing an image field in a template and follow accordingly. But the image is not showing in the template although the image is properly uploaded to the folder.

models.py

class Book(models.Model):
      book_thumbnail = models.ImageField(upload_to='images/%Y/%m/%d', blank=True, null=True)

views.py

def home(request):
    book = Book.objects.all()
    return render(request, 'books/books.html', context={'books': book})

template.html

<img class="group list-group-image" src="{{ books.book_thumbnail.url }}" width='240' alt="alt" />

settings.py

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

urls.py

urlpatterns = [
    path('books/', views.home),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  • 1) you need to check that template shows correct url instead of {{ books.book_thumbnail.url }} when template is rendered. 2) you need to check that MEDIA_ROOT shows to correct directory, there maybe problems with relative path – Sandro Sep 10 '18 at 15:38
  • everything seems right –  Sep 10 '18 at 15:54
  • can you just show what url was actually rendered by {{ books.book_thumbnail.url }} and what do you see if you print MEDIA_ROOT – Sandro Sep 10 '18 at 15:59

1 Answers1

0

printing media root works for me.

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
print(MEDIA_ROOT)

Here is what i just edited in settings.py