简体   繁体   中英

Displaying an image from a model in a Django template

I'm trying to access an image from a model in my template:

In my template , I have:

{% for server in servers %}
  <div class="hs-item set-bg" data-setbg="{{ server.image.url }}">
     <div class="hs-text">
        <div class="container">
           <h2>The Best <span>Games</span> Out There</h2>
             <p>Lorem ipsum.</p>
              <a href="#" class="site-btn">Read More</a>
        </div>
     </div>
 </div>
{% endfor %}

And my models look like this:

class Server(models.Model):
    Name = models.CharField(max_length=100)
    IP = models.CharField(max_length=50)
    Port = models.IntegerField()
    Image = models.ImageField(default='default.jpg', upload_to='server_pics')

    def __str__(self):
        return str(self.Name) if self.Name else ''

I've added this to my settings.py :

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

And this to my urls.py :

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

But it doesn't display the image, and I don't get an error in the console... Not sure what I'm doing wrong here...

However, when I replace {{ server.image.url }} in my template by a static image, it works.

I found the solution, I had to change server.image.url to server.Image.url, which fixed the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM