AttributeError: 'module' object has no att

2019-06-04 03:50发布

问题:

#!/usr/bin/env python
# coding: utf-8

import os, sys, subprocess, time, re, ast

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webapi.server.project.settings")

import django
django.setup()

from django.apps import apps

try:

cchilders: ./write_creation_tests.py 
Traceback (most recent call last):
  File "./write_creation_tests.py", line 17, in <module>
    django.setup()
AttributeError: 'module' object has no attribute 'setup

if I remove the setup attempt I can't import apps:

#!/usr/bin/env python
# coding: utf-8

import os, sys, subprocess, time, re, ast

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webapi.server.project.settings")

from django.apps import apps

try:

cchilders: ./write_creation_tests.py 
Traceback (most recent call last):
  File "./write_creation_tests.py", line 19, in <module>
    from django.apps import apps
ImportError: No module named apps

in manage.py:

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webapi.server.project.settings")

thus my os.environ setting matches the format in another project. I run this script the same way in the other django project and it works, but not in my webapi. These projects are on pythonpath. How can I setup django? Thank you

回答1:

You need to upgrade your version of Django to a supported version. Newer versions of Django have the setup function. See the list of supported Django versions

The answer was in the comments:

The error suggests that you're running Django 1.6 or older, in which case you don't need to call setup(). – knbk Mar 23 '16 at 16:14

The django.apps module was added in Django 1.7. You'll need to upgrade Django or change the script to work with your version of Django. Upgrading is recommended, because 1.7 and older are now end of life, and do not receive security fixes. – Alasdair Mar 23 '16 at 16:23

Both django.setup() and django.apps were added in 1.7.