settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROO" /> settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROO" /> settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROO"/>

Can't show image from database in django

38 views Asked by At

index.html

<img src="{{beat.image.url}}" class="card-img-top" alt="{{beat.name}}">

settings.py

STATIC_URL = '/static/'

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

models.py

image = models.ImageField(upload_to='images', blank=True)

urls.py

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

beat.image.url not working

1

There are 1 answers

2
Ragas Imger On

You may have passed queryset in the template. If that's the case, you need to access that with for loop in templates like this:

{% for content in beat %}
<img src="{{content.image.url}}" class="card-img-top" alt="{{content.name}}">
{% endfor %}

Please post the views.py so that we can look further to solve the issue.

Edit your urls.py first:

from django.conf import settings
from django.conf.urls.static import static
from django.views.static import serve
from django.urls import path, re_path

urlpatterns = [
    # Other routes here
    re_path(r'^media/(?P<path>.*)$', serve,
        {'document_root': settings.MEDIA_ROOT}),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)