在django中将动态变量从父模板传递到子模板

问题描述 投票:0回答:1

我有一个包含子模板songs.html的模板addToPlaylist.html。我需要要动态添加到播放列表中的歌曲的标题。这是songs.html的代码,其中包括addToPlaylist.html

                {% for song in songs  %}
                <div class="col-16 col-sm-4 col-md-3 col-lg-2 single-album-item">
                    <div class="single-album">
                        <img src="{{MEDIA_URL}}{{song.image.url}}" alt="">
                        <div class="album-info">
                            <a href="{% url 'playSong' 'song' song.tittle %} ">
                                <h5>{{song.tittle}}</h5>
                            </a>
                            <p>{{song.album}}</p>
                            {% include "songs/addToPlaylist.html" with song_to_add=song.tittle %}
                            <a data-toggle="modal" href="#addToPlaylist" style="color: dimgrey; font-size: small;">Add to Playlist</a>
                        </div>
                    </div>
                </div>
                {% endfor %}

这是addToPlaylist.html的代码

              <div class="form-group" style="width: 100%;">
                  <ul class="list-group list-group-flush" style="width: 100%;">
                    {% for playlist in playlists %}
                    <li class="list-group-item"><a href="{% url 'addToPlaylist' playlist.name song_to_add %}">{{playlist.name}}</a></li>
                    {% endfor %}
                </ul>
                  </div>

但是将动态值分配给song_to_add不起作用。该变量不会传递到子模板。

这是传递播放列表值的views.py代码

    if request.user.is_authenticated:
        playlists = Playlist.objects.filter()
    songs = Song.objects.all()
    return render(request, "songs\\songs.html", {'songs': songs, 'playlists':playlists,})

这是我的Song模型

class Song(models.Model):
    GENRES = [
        ('Rock','Rock'),
        ('Hip Hop','Hip Hop'), 
        ('Blues', 'blues'), 
        ('Heavy Metal', 'Heavy Metal'), 
        ('Classical', 'Classical'), 
        ('Funk', 'Funk')]
    tittle = models.CharField(max_length=255)
    album = models.CharField(max_length=255, null = True, blank = True)
    genre = models.CharField(max_length = 30, choices=GENRES)
    image = models.ImageField(upload_to='images/', blank = True , null = True)
    songFile = models.FileField(upload_to='musics/', help_text=("Allowed type - .mp3, .wav, .ogg"))
    uploaded_at = models.DateTimeField(auto_now_add=True)

而且,我尝试了this solution

python django variables django-templates include
1个回答
0
投票

您的<h5>{{song.tittle}}</h5>呢?如果您削减了错误的代码,可以正常显示吗?我认为您的{{song.tittle}}返回空字符串或无,必须将其重写为{{song.title}}

如果无法解决您的问题,请显示您的歌曲型号代码。

© www.soinside.com 2019 - 2024. All rights reserved.