user6781560
user6781560

Reputation:

django type error cannot concatenate str and deferred attribute objects

In the code I am connecting to my database and creating a bunch of links. I am following the tutorial here: https://www.youtube.com/watch?v=b0d09mYsORs

with the code as is, the instructor is able to run the code. I am not.

I am unsure what a deferred object is, and what the issue may be. I have read the docs for a while, and am requesting some assistance while I continue to push.

The code:

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

when I try and cast the Album.albumTitle attribute as a string, I receive zero content.

Upvotes: 1

Views: 794

Answers (3)

Pratosh Kumar
Pratosh Kumar

Reputation: 1

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

This worked for me, I was facing the same issue and following Bucky.As album is

Upvotes: -1

Hybrid
Hybrid

Reputation: 7049

Album in Album.albumTitle should be lowercase, or else you are accessing the class, and not the specific instance you want.

Corrected code:

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

Upvotes: 3

matias elgart
matias elgart

Reputation: 1181

use your same technique as the line above it. change:

html += '<a href ="' + url + '">' + Album.albumTitle + '</a><br>'

to:

html += '<a href ="' + url + '">' + str(Album.albumTitle) + '</a><br>'

Upvotes: -1

Related Questions