kaycee
kaycee

Reputation: 211

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 !

Upvotes: 4

Views: 2441

Answers (3)

Moses Noel
Moses Noel

Reputation: 25

Well, I worked on above solution of Mr @Dominic Rodger, but because am using Django version 3.2 it did not worked for me. Therefore, the problem may remain the same but according to how Django version changes, the way to solve them sometimes become different. If you're using Django 3.x use below solution.

In views.py

def songs(request):
   song_list = Song.objects.all().order_by('-created_at')[:5]
   song_list = {'song_list':song_list}
   return render(request, 'artists/songs.html', song_list)

In your HTML Template use code below

<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
    <thead>
        <tr>
            <th>Artist - Song Title</th>
        </tr>
    </thead>
        <tbody>
            {% for song in song_list %}
            </tr>
                <td>{{ song.artist.name }} - {{ song.title }}</td> 
            <tr>
            {% endfor %}
        </tbody>
</table> 

In urls.py

path('songs/', views.songs, name='songs'),

If you're running source code from localhost, then type on your browser http://127.0.0.1:8000/songs/

Thank you ....

Upvotes: 1

Dominic Rodger
Dominic Rodger

Reputation: 99751

Try changing your template code to:

{% for song in song_list %}
  {% for artist in song.artists.all %}
    {{ artist.name }} - {{ song.title }} 
  {% endfor %}
{% endfor %}  

Upvotes: 7

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798536

artists is another type of manager, so you have to iterate through artists.all and print the name attribute of each element.

Upvotes: 1

Related Questions