【问题标题】:image not showing in the templates in Django图像未显示在 Django 的模板中
【发布时间】:2022-01-21 13:22:41
【问题描述】:

当我从数据库中添加歌曲时,一切正常,但图像未显示在模板中。我该如何解决?

这是我的模板:

 {% for audio in songs %}

 <div class="player">

    <div class="imgBx">
      <div>
        <p>{{audio.book_title}}</p>

        <p>{{audio.artist}}</p>

        <p>{{audio.author}}</p>
      </div>
        <img src="{{object.image_url}}" alt="">
    </div>
    <audio controls>

    <source src="{{audio.file.url}}" type="audio/mp3">
    </audio>
 </div>
 {% endfor %}

这是我的models.py:

from django.db import models

# Create your models here.
class Audio(models.Model):
    book_title = models.CharField(max_length=100, null=False, blank=False)
    file = models.FileField(upload_to='file')
    author = models.CharField(max_length=100, null=False, blank=False)
    artist = models.CharField(max_length=100, null=False, blank=False)
    image = models.ImageField(upload_to=file, null=True, blank=False)

    def __str__(self):
        return self.book_title
        def image_url():
            if self.image and hasattr(self.image, 'url'):
                return self.image.url

这是我的views.py:

from django.shortcuts import render

from .models import Audio

# Create your views here.

def index(request):
    context = {'songs': Audio.objects.all()}
    return render(request, 'index.html', context)

【问题讨论】:

  • 必须在 settings.py 文件中设置你的 media_root 和 media_url 吗?如果不了解它们,请向我们展示您的项目的 urls.py 文件

标签: django django-models django-views django-templates


【解决方案1】:

您可以在 django 模型中使用 python Property,如下所示。

class Audio(models.Model):
    book_title = models.CharField(max_length=100, null=False, blank=False)
    file = models.FileField(upload_to="file")
    author = models.CharField(max_length=100, null=False, blank=False)
    artist = models.CharField(max_length=100, null=False, blank=False)
    image = models.ImageField(upload_to=file, null=True, blank=False)

    def __str__(self):
        return self.book_title

    @property
    def image_url(self):
        """
        Returns a image url if the audio has an image.
        """
        return self.image.url if self.image else None

【讨论】:

  • 先生不工作了
  • 您面临什么问题?当音频有图像时它返回 None 吗?尝试像这样更改模型中图像字段的upload_to image = models.ImageField(upload_to=file, null=True, blank=False)
  • 加油,我的朋友已经工作正常了。非常感谢
【解决方案2】:

我觉得你&lt;img src="{{object.image_url}}" alt=""&gt;有错,应该是&lt;img src="{{audio.image.url}}" alt=""&gt;

【讨论】:

  • 非常感谢我的朋友,现在一切正常。我为你感到骄傲
猜你喜欢
  • 2021-12-10
  • 1970-01-01
  • 1970-01-01
  • 2019-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-16
相关资源
最近更新 更多