import module in Django

Question:

I have a project with structure like on this picture.
Folders structure

Where ‘backend’ folder is Django project folder.
I need to import module from another folder ‘main’ inside Django app file, i.e. import main.Text_Generator in backend.app.views file.

I tried: from ...main.Text_Generator import *. This raise an error while running a server: "attempted relative import beyond top-level package"

And from main.Text_Generator import *, also error "No module named ‘main’"

What is the correct way to do such import?

Asked By: Leonid Efremov

||

Answers:

Add this:

import sys
sys.path.append("..")

And then you should be able to get it with:

from main.Text_Generator import *
Answered By: NixonSparrow

You’re using a module outside your Django project. I would recommend moving the folder inside your project directory [or app directory] rather than messing with your PATH. If you move main inside backend your existing stuff will work.

Answered By: Pan Dango
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.