Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing foreignKey inside the template

well it's quiet simple. 2 models with ManyToMany relation:

class Artist(models.Model):
   name = models.CharField(max_length=100, unique=True)
   slug = models.SlugField(max_length=100, unique=True,
            help_text='Uniq value for artist page URL, created from name')
   birth_name = models.CharField(max_length=100, blank=True)


class Song(models.Model):
   title = models.CharField(max_length=255)  
   slug = models.SlugField(max_length=255, unique=True,
            help_text='Unique value for product page URL, create from name.')
   youtube_link = models.URLField(blank=False)
   artists = models.ManyToManyField(Artist)

my view suppose to display latest 5 songs:

def songs(request, template_name="artists/songs.html"):
   song_list = Song.objects.all().order_by('-created_at')[:5]
   return render_to_response(template_name, locals(),
                          context_instance=RequestContext(request))

and the problem is in the template... i want to display the artist name but just dont realy know how to do it, i tried:

{% for song in song_list %}
    {{ artists__name }} - {{ song.title }} 
{% endfor %}  

would appreciate any help !

like image 737
kaycee Avatar asked Jan 23 '23 18:01

kaycee


1 Answers

Try changing your template code to:

{% for song in song_list %}
  {% for artist in song.artists.all %}
    {{ artist.name }} - {{ song.title }} 
  {% endfor %}
{% endfor %}  
like image 177
Dominic Rodger Avatar answered Jan 25 '23 16:01

Dominic Rodger