SBrain SBrain - 3 years ago 139
Python Question

Why I have only one album?

I'm started learning Django and there are some problems with it:)
This is views.py

from django.http import HttpResponse
from .models import Album


def index(request):
all_albums = Album.objects.all()
html = ''
for album in all_albums:
url = '/music/' + str(album.id) + '/'
html += '<a href ="' + url + '">' + album.album_title + '</a><br>'
return HttpResponse(html)


There is class Album.
This is models.py

from django.db import models


class Album(models.Model):
artist = models.CharField(max_length=250)
album_title = models.CharField(max_length=250)
genre = models.CharField(max_length=250)


I created two albums(for example "Red" and "Destiny" and I want my albums with references appears on page http://127.0.0.1:8000/music/ . But there is only one album "Red". I think that my loop "for" doesn't working, but I can't understand why.
I hope you'll understand my question.
Help me please, I want to sleep :)

Answer Source

any way, please override your code in pythonic style, and may be it help

def index(request):
    all_albums = Album.objects.all()
    html = []
    for album in all_albums:
        url = '/music/%s/' % album.id
        html.append('<a href ="%s">%s</a><br>' % (url, album.album_title))
    return HttpResponse(''.join(html))

for detail read join docs

and by comment of @Björn Kristinsson string params by % it is older method, better solution is

def index(request):
    all_albums = Album.objects.all()
    html = []
    for album in all_albums:
        url = '/music/{id}/'.format(id=album.id)
        html.append('<a href ="{url}">{title}</a><br>'.format(url=url, title=album.album_title))
    return HttpResponse(''.join(html))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download