开发者

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_leng开发者_Python百科th=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 !


Try changing your template code to:

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


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


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 ....

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜