Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Django Basics Test Time Django TDD

Ker Zhang
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Ker Zhang
Full Stack JavaScript Techdegree Graduate 29,113 Points

Can't find anything wrong but always "Not all tests are passing"

Can't find the root cause, and I've compared by code with all the code in the community. I've also tried to run the code in Workspaces, there was a error "ImportError: cannot import name 'Performer'.

Pls help. Thanks!

songs/models.py
from django.db import models

# Write your models here
class Song(models.Model):
    title = models.CharField(max_length=255)
    artist = models.CharField(max_length=255)
    length = models.IntegerField()
    performer = models.ForeignKey('Performer')

    def __str__(self):
        return self.title


class Performer(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name
songs/views.py
from django.shortcuts import render

from .models import Song, Performer


def song_list(request):
    songs = Song.objects.all()
    return render(request, 'songs/song_list.html', {'songs': songs})


def song_detail(request, pk):
    song = get_object_or_404(Song, pk=pk)
    return render(request, 'songs/song_detail.html', {'song': song})


def performer_detail(request, pk):
    performer = get_object_or_404(Performer, pk=pk)
    songs = Song.objects.filter(performer=performer)
    return render(request, 'songs/performer_detail.html', {'performer': performer, 'songs': songs})
songs/templates/songs/performer_detail.html
{% extends 'base.html' %}

{% block title %}{{ performer }}{% endblock %}

{% block content %}
<h2>{{ performer }}</h2>
  {% for song in songs %}
   {{ song }}
  {% endfor %}
{% endblock %}

4 Answers

Christopher Shaw
seal-mask
PLUS
.a{fill-rule:evenodd;}techdegree seal-36
Christopher Shaw
Python Web Development Techdegree Graduate 58,248 Points

Good Day,

  1. In views, you need to import get_object_or_404.

  2. Also in views, you dont need to get the songs in performer_detail as below:

views:

def performer_detail(request, pk):
    performer = get_object_or_404(Performer, pk=pk)
    return render(request, 'songs/performer_detail.html', {'performer': performer})

performer_detal

  {% for song in performer.song_set.all %}
<li>{{ song }}</li>
  {% endfor %}
Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Does your code pass the tests provided in the workspace? If so, it'll pass the challenge. Right now, I get a failing test with a missing song title.

Ker Zhang
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Ker Zhang
Full Stack JavaScript Techdegree Graduate 29,113 Points

Dear teacher Kenneth,
Things were very strange on my computers (after fix all the problem mentioned by you and Chris):

  1. I always get "ImportError: cannot import name 'Performer'." while running the test in Workspace.
  2. I tried the makemigrations in Workspace, it returned an error said can't find the performer_detail in songs.views. But as a matter of fact, it was there.
  3. I created a Django project with Pycharm IDE on may computer and moved all my code to that project, ran the test there, it Passed without any problem!
  4. Finally, just for the last try, I switched my broswer from Chrome to the system-build-in IE version 11. It runs very slow, but, the test PASSED!

Well, that's not a bad experience, I learned a lot of things from this 'trouble'.

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Hmm. The import thing is definitely weird. Can you share your workspace with me? There's a share button on the top right, I think.

I don't see how changing your browser would affect the tests at all since none of them use a browser.

Ker Zhang
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Ker Zhang
Full Stack JavaScript Techdegree Graduate 29,113 Points

I see three buttons on the top right: Snapshot, Fork, Preview.

Do you mean Snapshot is the sharing? I took two shots anyway, but the contents was empty, my code didn't show there.

https://w.trhou.se/arf8y1gsbl

https://w.trhou.se/jg4vtpx8kb

Here's are my final code which passed in IE and Pycharm. =========models==========

from django.db import models


# Write your models here
class Song(models.Model):
    title = models.CharField(max_length=255)
    artist = models.CharField(max_length=255)
    length = models.IntegerField()
    performer = models.ForeignKey("Performer")

    def __str__(self):
        return "{} by {}".format(self.title, self.artist)


class Performer(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

========views================

from django.shortcuts import render, get_object_or_404

from .models import Song, Performer


def song_list(request):
    songs = Song.objects.all()
    return render(request, 'songs/song_list.html', {'songs': songs})


def song_detail(request, pk):
    song = get_object_or_404(Song, pk=pk)
    return render(request, 'songs/song_detail.html', {'song': song})


def performer_detail(request, pk):
    performer = get_object_or_404(Performer, pk=pk)
    songs = Song.objects.filter(performer=performer)
    return render(request, 'songs/performer_detail.html', {'performer': performer, 'songs': songs})

================ performer_detail=============

{% extends 'base.html' %}

{% block title %}{{ performer }}{% endblock %}

{% block content %}
<h2>{{ performer }}</h2>
  {% for song in songs %}
   {{ song }}
  {% endfor %}
{% endblock %}

================Test Result in workspace==================

treehouse:~/workspace/karaoke$ python manage.py test                                                                                       
Creating test database for alias 'default'...                                                                                              
E                                                                                                                                          
======================================================================                                                                     
ERROR: songs.tests (unittest.loader._FailedTest)                                                                                           
----------------------------------------------------------------------                                                                     
ImportError: Failed to import test module: songs.tests                                                                                     
Traceback (most recent call last):                                                                                                         
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/unittest/loader.py", line 428, in _find_test_path                                    
    module = self._get_module_from_name(name)                                                                                              
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name                              
    __import__(name)                                                                                                                       
  File "/home/treehouse/workspace/karaoke/songs/tests.py", line 5, in <module>                                                             
    from .models import Performer, Song                                                                                                    
ImportError: cannot import name 'Performer'                                                                                                


----------------------------------------------------------------------                                                                     
Ran 1 test in 0.026s                                                                                                                       

FAILED (errors=1)                                                                                                                          
Destroying test database for alias 'default'...                                                                                            
treehouse:~/workspace/karaoke$               

=========== Error while trying to makemigrations in Workspaces===========

    self.check()                                                                                                                           
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/core/management/base.py", line 426, in check                    
    include_deployment_checks=include_deployment_checks,                                                                                   
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/core/checks/registry.py", line 75, in run_checks                
    new_errors = check(app_configs=app_configs)                                                                                            
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config              
    return check_resolver(resolver)                                                                                                        
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver                
    for pattern in resolver.url_patterns:                                                                                                  
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/utils/functional.py", line 33, in __get__                       
    res = instance.__dict__[self.name] = self.func(instance)                                                                               
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/core/urlresolvers.py", line 417, in url_patterns                
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)                                                            
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/utils/functional.py", line 33, in __get__                       
    res = instance.__dict__[self.name] = self.func(instance)                                                                               
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module              
    return import_module(self.urlconf_name)                                                                                                
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/importlib/__init__.py", line 126, in import_module                                   
    return _bootstrap._gcd_import(name[level:], package, level)                                                                            
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import                                                                           
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load                                                                        
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked                                                               
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked                                                                        
  File "<frozen importlib._bootstrap_external>", line 662, in exec_module                                                                  
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed                                                             
  File "/home/treehouse/workspace/karaoke/karaoke/urls.py", line 23, in <module>                                                           
    url(r'^songs/', include('songs.urls', namespace='songs')),                                                                             
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/conf/urls/__init__.py", line 52, in include                     
    urlconf_module = import_module(urlconf_module)                                                                                         
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/importlib/__init__.py", line 126, in import_module                                   
    return _bootstrap._gcd_import(name[level:], package, level)                                                                            
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import                                                                           
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load                                                                        
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked                                                               
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked                                                                        
  File "<frozen importlib._bootstrap_external>", line 662, in exec_module                                                                  
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed                                                             
  File "/home/treehouse/workspace/karaoke/songs/urls.py", line 6, in <module>                                                              
    url(r'performer/(?P<pk>\d+)/$', views.performer_detail, name='performer'),                                                             
AttributeError: module 'songs.views' has no attribute 'performer_detail'                                                                   
treehouse:~/workspace/karaoke$
Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Hmm, that all passes fine for me in the code challenge. I'll set up a Workspace to try it there, too. I'll let you know if I find out anything.

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

It passes for me in Workspaces, too. That's weird that you're having issues on it. Sorry about that, I'll point our Workspaces team to this thread, maybe they have an idea that I don't.

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Both of your snapshots just have the default files in them. Make sure you've saved all of your files before doing a snapshot or running tests.

Ker Zhang
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Ker Zhang
Full Stack JavaScript Techdegree Graduate 29,113 Points

I guess we found the cause. The first problem might be, I never saved my code in WorkSpaces, I just pasted my code and ran. However, I didn't save the code in IE either but didn't know why it pass there. Today, when I saw your reply, I thought maybe all the problem was because of the 'saving' thing. So I did a try again. Logged all the history below for your refernence. Basically I did it this way:

  1. Don't save code and run test, failed as it was.
  2. Then saved by code and run test again, got another fail.
  3. Made migration and ran test again. Pass. One more comments: In the past, I tried to run the test on my MacBook OS X, a MintLinux workstation and a HP laptop with Windows 7, all with Chrome. The only success was on Windows 7 in IE broswer.

========================================================================== treehouse:~/workspace$ cd karaoke/
treehouse:~/workspace/karaoke$ python manage.py test
Creating test database for alias 'default'...

E

ERROR: songs.tests (unittest.loader._FailedTest)

ImportError: Failed to import test module: songs.tests
Traceback (most recent call last):
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/unittest/loader.py", line 428, in find_test_path
module = self._get_module_from_name(name)
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name
__import
_(name)
File "/home/treehouse/workspace/karaoke/songs/tests.py", line 5, in <module>
from .models import Performer, Song
ImportError: cannot import name 'Performer'


Ran 1 test in 0.000s

FAILED (errors=1)
Destroying test database for alias 'default'...

I SAVED ALL MY CODE HERE, AND THEN RUN TEST AGAIN

treehouse:~/workspace/karaoke$ python manage.py test
Creating test database for alias 'default'...
Traceback (most recent call last):
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in exec ute
return self.cursor.execute(sql, params)
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: songs_song

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/core/management/init.py", line 353, in execute_from_command_line
utility.execute()
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/core/management/init.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv
super(Command, self).run_from_argv(argv)
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/core/management/commands/test.py", line 90, in handle
failures = test_runner.run_tests(test_labels)
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/test/runner.py", line 532, in run_tests old_config = self.setup_databases()
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/test/runner.py", line 482, in setup_dat abases
self.parallel, **kwargs
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/test/runner.py", line 726, in setup_dat abases
serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True),
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 78, in create_test_db
self.connection.test_serialized_contents = self.serialize_db_to_string()
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 122 , in serialize_db_to_string
serializers.serialize("json", get_objects(), indent=None, stream=out)
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/core/serializers/
init.py", line 129 , in serialize
s.serialize(queryset, **options)
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/core/serializers/base.py", line 79, in serialize
for count, obj in enumerate(queryset, start=1):
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 118 , in get_objects
for obj in queryset.iterator():
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/db/models/query.py", line 52, in __iter _

results = compiler.execute_sql()
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 848, i n execute_sql
cursor.execute(sql, params)
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in exec ute
return self.cursor.execute(sql, params)
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/db/utils.py", line 95, in exit
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in exec ute
return self.cursor.execute(sql, params)
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: songs_song

I MADE MIGRATION THEN ###

treehouse:~/workspace/karaoke$ python manage.py makemigrations
Migrations for 'songs':
0001_initial.py:
- Create model Performer
- Create model Song
treehouse:~/workspace/karaoke$ python manage.py migrate
Operations to perform:
Apply all migrations: auth, admin, sessions, songs, contenttypes
Running migrations:
Rendering model states... DONE
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
treehouse:~/workspace/karaoke$

RUN TEST, PASS! ###

treehouse:~/workspace/karaoke$ python manage.py test
Creating test database for alias 'default'...

.....

Ran 5 tests in 0.094s

OK
Destroying test database for alias 'default'...