import django models classes into utility module

两盒软妹~` 提交于 2020-07-22 21:38:42

问题


I have two model classes in my models.py module in the default location.

PythonFinal
    |_   manage.py
    |_  template
    |_ PythonFinal
    |       |_  __init__.py
    |       |_  settings.py
    |       |_  urls.py
    |       |_  swgi.py
    | 
    |      
    |___ fertility
            |_  __init__.py
            |_  models.py
            |_  tests.py
            |_  views.py
            |_  dateUtils.py

I simply want to import the classes into dateUtils.py

from fertility.models import Cycle, Period

if __name__ == '__main__':
    p1 = Period(periodFirstDay='2012-7-26' , periodNumber=4) 

If I run this module I get

ImportError: no module named fertility

If I try to import models from the python commandline I get

import models    
Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "models.py", line 1, in <module>
        from django.db import models
      File "/usr/local/lib/python2.6/dist-packages/django/db/__init__.py", line 11, in <module>
        if DEFAULT_DB_ALIAS not in settings.DATABASES:
      File "/usr/local/lib/python2.6/dist-packages/django/utils/functional.py", line 184, in inner
        self._setup()
      File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 40, in _setup
        raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
    ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

I added my projects root folder to the PYTHONPATH in ~/.bashrc. My wsgi.py reads

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "PythonFinal.settings")

I do not think it is not a circular import because I get the ImportError instead of a NamingError, and I simply don't have many imports yet. For obvious reasons I need to be able to import my model to other modules I can unit test or I need another simple workflow that accomplishes the same.


回答1:


If PythonFinal is in /home/users/jeremy/django/PythonFinal, then /home/users/jeremy/django should be in your PYTHONPATH environment variable, and DJANGO_SETTINGS_MODULE should be set to "PythonFinal.PythonFinal.settings". Then you can use

from PythonFinal.fertility.models import Cycle, Period

from the Python command line.

It is, however, more common to have the settings.py file in the same folder as manage.py, and a number of tools and tutorials expect this setup...



来源:https://stackoverflow.com/questions/11704980/import-django-models-classes-into-utility-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!