[Django]-Django admin causing AttributeError

2πŸ‘

I ran into this error when trying to run a test module residing outside my django project (a practice django doesn’t seem to support):

$ tree
.
β”œβ”€β”€ example_project
β”‚Β Β  β”œβ”€β”€ example_app
β”‚Β Β  β”‚Β Β  β”œβ”€β”€ __init__.py
β”‚Β Β  β”‚Β Β  └── models.py
β”‚Β Β  β”œβ”€β”€ __init__.py
β”‚Β Β  β”œβ”€β”€ manage.py
β”‚Β Β  └── project
β”‚Β Β   Β Β  β”œβ”€β”€ __init__.py
β”‚Β Β   Β Β  β”œβ”€β”€ settings.py
β”‚Β Β   Β Β  β”œβ”€β”€ urls.py
β”‚Β Β   Β Β  └── wsgi.py
└── test
    └── test_example_app.py

The error was caused by django assuming a different import path at different points in the process so I resolved it by appending to sys.path. I’d be hesitant to do this in a production environment but I can accept some hackiness in tests.

Here’s what I ended up with in test_example_app.py:

import os
import sys

import django
from django.conf import settings
from django.test import LiveServerTestCase
from django.test.utils import get_runner

class TestExampleApp(LiveServerTestCase):
   ...

if __name__ == '__main__':
    sys.path.append(os.path.realpath('./example_project'))
    os.environ['DJANGO_SETTINGS_MODULE'] = 'example_project.project.settings'
    django.setup()

    sys.path.append(os.path.realpath('./example_project/project'))
    testrunner = get_runner(settings)()
    failures = testrunner.run_tests(['test_example_app'])
    sys.exit(bool(failures))
πŸ‘€Ryne Everett

1πŸ‘

The solution, as strange as it seems to me, was I had specified the root folder as the start of the import for books.models in the views.py file. This seemed not just to blow up the admin start, but the error that it gave didn’t give much, if any, indication of the root issue. It was only when I rolled back to python 2.7 that the error message gave me some indication of the root of the problem.
I’m guessing that this is classic neophyte stuff, since it now seems obvious that the β€˜root’ of the site should be the folder with manage.py in it, and therefore shouldn’t be in any path specification. Although the book doesn’t seem to state that…

πŸ‘€Arana

Leave a comment