Display images in Django
This is how i got it working.
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 ...
image = models.ImageField(upload_to='img')
urls.py(project's)
if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
template (.html)
<img src="{{ post.image.url }}" alt="img">
Do something like this. This code is working in my app.
views.py:
def list(request):
images = Image.objects.all()
return render(request, "list.html", {'images': images})
list.html:
{% for i in images %}
<img src="{{ i.image.url }}" width="500px"/>
{% endfor %}