Arsh Ergon
Arsh Ergon

Reputation: 160

Display images form the admin panel

I want to make a app in which admin upload a image on admin panel and it display on the template. I'm know there are some question related to this but I tried all of them but still can't display image. Django version: 2.1.4 python version: 3.6.7

In setting.py

STATIC_URL = '/static/'

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'image')

In model.py

from django.db import models

class ImageModel(models.Model):
    caption = models.CharField(max_length=40)
    image = models.ImageField(upload_to='uploadImage', blank=True)

    def __str__(self):
        return self.caption 

In view.py

from django.shortcuts import render
from .models import ImageModel

def image_page(request):
    images = ImageModel.objects.all()
    return render(request, 'input/hello.html', {'image':images})

In urls.py

from django.contrib import admin
from django.urls import path, include
from image import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.image_page),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

In imageShow.html

<img src="{{ ImageModel.image.url }}" alt="image" /> 

doing this show me a broken image and some time the full url of the image(where is the image is saved) What I'm doing wrong. I try to print variable images in views.py and it print my caption("image") so it means that it sending caption in img tag not the image itself? should I make a new class of ImageUpload? thanks in advance

Upvotes: 0

Views: 650

Answers (1)

ruddra
ruddra

Reputation: 51948

You need to iterate through ImageModel queryset (which you are sending as context via variable image) and show the image in template, like this:

{% for im in image %}
    <img src="{{ im.image.url }}" alt="image" />
{% endfor %}

Upvotes: 2

Related Questions