When you render the page and load the form for the first time is_favorite for all songs is False.
In the given example album has four songs. There is one radio control for each song. They have different ids and different value (the id of the song) but the same name ('song').
When you submit the form you post one key-value pair - {'song':song.id} where song.id is the respective id of the song (the value of the selected radio control).
Now your python function
at the end of the python function you render the same page, however now the album that you pass has changed and one song is favorite. That is why the respective lines you identified correctly will execute and show a star next to the song. If you now submit the form with the same song selected, it will in-favorite it and next time page is rendered it will not display star next to it.
as a side note that
In the given example album has four songs. There is one radio control for each song. They have different ids and different value (the id of the song) but the same name ('song').
When you submit the form you post one key-value pair - {'song':song.id} where song.id is the respective id of the song (the value of the selected radio control).
Now your python function
selected_song = album.song_set.get(pk=int(request.POST['song'])) if selected_song.is_favourite: selected_song.is_favourite = False else: selected_song.is_favourite = True selected_song.save()here it basically toggle the is_favourite property of the song - if it was True it will become False and vice-verse. This is important later on, because this is how you will in-favorite song that was previously favorite.
at the end of the python function you render the same page, however now the album that you pass has changed and one song is favorite. That is why the respective lines you identified correctly will execute and show a star next to the song. If you now submit the form with the same song selected, it will in-favorite it and next time page is rendered it will not display star next to it.
as a side note that
if selected_song.is_favourite: selected_song.is_favourite = False else: selected_song.is_favourite = Truecan be replaced with just
selected_song.is_favourite = not selected_song.is_favourite
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs