[Answer]-Django: How to write an if statement

1👍

I don’t think so, in the template language if statement you can use round bracket it won’t parse. Try by removing it…

{% if songs.artist.firstname == singer.firstname and songs.artist.lastname==singer.lastname%}

0👍

It seems that your view should be handling more of this logic. Like Raunak Agarwal mentioned if you are passing your song or songs in to the template then each one is going to be the same.

It’s very strange as well to be doing a

{% for songs in song %}

That just doesn’t read right.

I would visit the view a little closer. I had written some more below. After looking over your code though taking a look at the view as well as the model would shed some light on things and allow for a much better help/answer to be given.

0👍

As you said My song class contains a foreign key of an artist along with the song title. – why don’t you just use the regroup feature?

{% regroup song by artist as artist_list %}

<ul>
{% for artist in artist_list %}
    <li>{{ artist.grouper }}
    <ul>
        {% for songs in artist.list %}
          <li>{{ songs.title }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>

0👍

Yes, your if song line is incorrect. It’s quite clear from the template that you don’t even have a song attribute at that point. Where is it supposed to be coming from? Presumably it’s a related set on singer, but you haven’t said so in the template.

You probably want something like this:

{% for singer in artist %}
    <li>{{ singer.firstname }} {{ singer.lastname }}
    {% with songs as singer.song_set.all %}
        {% if songs %}
            <ul>
                {% for song in songs %}
                    <li>{{ song.title }}</li>
                {% endfor %}
            </uL>
        {% endif %}
    {% endwith %}
    </li>
{% endfor %}

I’ve also removed that comparison of artist firstname and lastname, that didn’t seem to make sense: you’re already iterating through the set of songs from that artist, so no comparison is needed.

Leave a comment