【发布时间】: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