【问题标题】:How to add songs to my templates in views如何在视图中将歌曲添加到我的模板
【发布时间】:2022-01-19 23:00:22
【问题描述】:

如果我从我的管理面板发布一首歌曲,我希望歌曲列表出现在模板中,我已经创建了一个允许我发布它的模型,但我不知道如何创建一个允许发布的视图要出现在模板中的歌曲,请问我该怎么做?

这是我的空视图 视图.py

from django.shortcuts import render
from .models import Audio

# Create your views here.
def index(request):
    return render(request, 'index.html')

这是我创建的 models.py 模型.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)

【问题讨论】:

    标签: python django templates django-views


    【解决方案1】:

    您将 Audio 对象的查询集传递给模板:

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

    在模板中我们可以枚举歌曲:

    {% for audio in songs %}
        {{ audio.book_title }} by {{ audio.artist }} </br>
    {% endfor %}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      • 2017-01-11
      • 1970-01-01
      • 2022-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多