0

I am having trouble on how to display an image on html? i just want to display all image that saves on my database

{% for banner in banners %}
<div class="mySlides fade">
  <div class="numbertext">1 / 3</div>
  <img class="d-block w-100" src="{{ banner.banner }}" style="width:100%">
  <div class="text">{{banner.title}}</div>
</div>
{% endfor %}

model

class Banner(models.Model):
    banner = models.ImageField(upload_to='image/', null=True, blank=True)

views

def homepage(request):
    banners = Banner.objects.all()
    return render(request, 'mysite/homepage.html', {'banners': banners})

result

enter image description here

2 Answers 2

1

Use the 'url' property of the ImageField.

Try this:

{{ banner.banner.url }}
Sign up to request clarification or add additional context in comments.

8 Comments

Hi Noman, I've tried youre answer but it didnt work on my end
What is the error you are getting?
"didn't work" is not a good problem description... what happened? if you view source on the generated page, what is generated? if you go to that url, what happens? etc. (you need to provide details)
I dont have error encountered the problem is it didnt display the image
@NomanGhani please see the image i posted, thanks
|
1

models.py

class Banner(models.Model):
    banner = models.ImageField(upload_to='image/', null=True, blank=True)

    def get_banner_url(self):
        return self.banner.url

html

{% for banner in banners %}
<div class="mySlides fade">
  <div class="numbertext">1 / 3</div>
  <img class="d-block w-100" src="{{ banner.get_banner_url }}" style="width:100%">
  <div class="text">{{banner.title}}</div>
</div>
{% endfor %}

for be sure that your URL is coming try this(just for test):

 <div class="text">{{banner.get_banner_url }}</div>

if you can't see the URL that means it is about your media tags settings.py

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

main urls.py

urlpatterns = [  
  #your paths  
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.