Home > Mobile >  How can I import the file in Django from a folder without Errors
How can I import the file in Django from a folder without Errors

Time:05-12

Can someone help me with my problem? I have the following project structure:

check_project
--- check_app
--- check_project
--- modules
    --- __init__.py
    --- tools.py
    --- robots.py

I need to import my tools.py file inside robots.py And here is the problem. If I import it this way

from tools import *

I can run the file inside Visual Studio Code and it works. But when I run Django it gives an Error: "ModuleNotFoundError: No module named 'tools'"

And if I import it this way

from modules.tools import *

Django works fine. But when I run the file inside Visual Studio Code it gives Error: "ModuleNotFoundError: No module named 'modules'"

from tools import *

This works in Django. But in Visual Studio I have an Error: "ImportError: attempted relative import with no known parent package"

from check_project.modules.robots import *

This works in Django. But in Visual Studio I have an Error: "ModuleNotFoundError: No module named 'check_project'"

How can I fix this problem so, that it would work both in Django and in Visual Studio?

Thank you for your help )

CodePudding user response:

This will work:

from .tools import *

CodePudding user response:

This issue almost always occurs because you are using a flat file structure for your project, and you try to split the functionality into two files.

  1. First method

The easiest way to solve that is to import the file before calling his elements. First, do this:

import tools

And then if you have for instance a function called "myfunction()" in your tools.py file, then you can use this function as following:

var = tools.myfunction()
  1. Second method

If you are making a separate file to do helpful things, why not make it an actual package? It is actually much easier than you would think.

Change up your file structure so that the functionality you want to split out is in a separate folder and includes an empty init.py file. Something like this:

check_project
--- check_app
--- check_project
--- modules
    --- __init__.py
    --- robots.py
    --- tools
        --- __init__.py
        --- tools.py

And then, you can use your previous syntax:

from tools import *

Hope this help.

  • Related