2

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?

Michael Sun
  • 189
  • 3
  • 10

1 Answers1

1

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
Jrog
  • 1,469
  • 10
  • 29