Reputation: 63
I am facing this error in django python:
"UnboundLocalError at /myapp/" local variable 'album' referenced before assignment
I Created a class in models.py file and import in views but facing this error
Here is complete code of both files:
Models.py
from django.db import models
from django.db import models
class album(models.Model):
artist = models.CharField(max_length=250)
title = models.CharField(max_length=500)
gender = models.CharField(max_length=100)
def __str__(self):
return self.artist+'--'+self.title
views.py
from django.http import HttpResponse
from .models import album
def myapp(request):
all_albums = album.objects.all()
title = album.artist
html = ''
for album in all_albums:
url = '/myapp/' + str(album.id) + '/'
html += '<a href="' + url + '">' + title + '</a><br>'
return HttpResponse(html)
Upvotes: 1
Views: 261
Reputation: 27503
copy this totally and paste in your view
from django.http import HttpResponse
from .models import album
def myapp(request):
all_albums = album.objects.all()
html = ''
for al in all_albums:
url = '/myapp/' + str(al.id) + '/'
html += '<a href="' + url + '">' + al.artist + '</a><br>'
return HttpResponse(html)
Upvotes: 0
Reputation:
Move title inside the loop and better use loop variable name not like model
html = ''
for album_data in all_albums:
url = '/myapp/' + str(album_data.id) + '/'
title = album_data.artist
html += '<a href="' + url + '">' + title + '</a><br>'
return HttpResponse(html)
Upvotes: 2
Reputation: 13372
You are using the album
name for multiple variables, once as a model, and other times as an instance. Model names should ideally be CamelCased. After correcting the model name, move the title
variable assignment inside the for
loop. Only doing the latter would solve your problem for now, but if you stick to the styling guidelines (PEP-8) you wouldn't face such issues in the future.
models.py
...
class Album(models.Model):
artist = models.CharField(max_length=250)
...
views.py
...
from .models import Album
def myapp(request):
all_albums = Album.objects.all()
html = ''
for album in all_albums:
title = album.artist
url = '/myapp/' + str(album.id) + '/'
html += '<a href="' + url + '">' + title + '</a><br>'
...
Upvotes: 0
Reputation: 9235
Change the view like this,
def myapp(request):
all_albums = album.objects.all()
html = ''
for album in all_albums:
url = '/myapp/' + str(album.id) + '/'
html += '<a href="' + url + '">' + album.artist + '</a><br>'
return HttpResponse(html)
Upvotes: 1