简体   繁体   中英

How to import models from outside Django BASE_DIR

I am working on a Django app in which I want to import some class/function from generator.py into my views.py to process an user-submitted input. My folder structure looks like this:

project/
   models/
      __init__.py
      generator.py
   web/
      django/
         __init__.py
         settings.py
         urls.py
         wsgi.py
      django_app
         __init__.py
         views.py
         etc.

Inside views.py, I have

from ...models.generator import Generator

When I try to run server, what I get is:

ValueError: attempted relative import beyond top-level package

I've seen many answers, but most are about manipulating sys.path or changing PYTHONPATH. I'm not sure how and where to do either cause I'm rather new to Django.

Can someone tell me exactly which commands to run to allow the import to be done?

Import of python is based on sys.path and cannot be outside the top-level dir. More information .

That's mean, if you append top of BASE_DIR path in sys.path you can import. But it's a tricky way.

def import_function():
    import sys
    sys.path.append(os.path.dirname(BASE_DIR))
    module = __import__('models.generator')  # import code
    sys.path.pop()
    return module

g_module = import_function()
g_module.Generator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM