Reputation: 31
Currently working on a Django website and I'm having an issue importing a class and its attributes from my models.py
module into my views.py
module within my music app. From what I understand Django uses metaclasses to construct models, so the defined fields don't end up as attributes on the class. Is this the problem and if so how do I solve it?
Directory Structure:
music
migrations
templates
_init_
admin.py
apps.py
models.py
tests.py
urls.py
views.py
The code inside models.py
is:
from django.db import models
class Album(models.Model):
artist = models.CharField(max_length=250)
album_title = models.CharField(max_length=500)
genre = models.CharField(max_length=100)
album_logo = models.CharField(max_length=1000)
def __str__(self):
return self.album_title + ' - ' + self.artist
The code inside views.py
is:
from django.http import HttpResponse
from .models import Album
from django.template import loader
def index(request):
all_albums = Album.object.all()
template = loader.get_template('music/index.html')
context = {'all albums': all_albums,}
return HttpResponse(template.render(context, request))
def details(request, album_id):
return HttpResponse("<h2> Details for Album id: " + str(album_id) + " </h2>")
The Error:
ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package
Error Location:
from .models import Album
Upvotes: 3
Views: 6139
Reputation: 113
Your __str__
method must be defined into Album
class, otherwise self is undefined
Upvotes: 6