-1

How to access models/usrs from resources/user

├───models
|   └───user.py
├───resources
|   └───user.py

First I import it like this one:

from code.models.user import UserModel

But I got a compile-time error:

`Cannot find reference 'models' in 'code.py'`

And I tried another way like this one:

from ..models.user import UserModel

But I got a runtime error:

ImportError: attempted relative import beyond top-level package

And I added init.py in both files but still doesn't work.

enter image description here

And also I tried these solutions but they don't fix my issue, please help me

abbas jafari
  • 81
  • 1
  • 9

2 Answers2

1

Add the models and resources directories to your $PYTHONPATH or use sys.path:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

Or:

import sys
sys.path.insert(0, "/home/project-name/models")

Or add "__ init__.py" to code directory:

from code.models import user
  • Thank you @Little Bamboo, First) I don't try the first one Second) `import sys sys.path.insert(0, "D:\Projects\Python\UdemyProjects\SixSimplifying\code\models") import user` I got this error: `SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 18-21: truncated \UXXXXXXXX escape` Third) I got this error: `Cannot find reference 'models' in 'code.py' ` Can you give more detailed advice? – abbas jafari Sep 21 '21 at 18:01
  • This is because the string you're using sees the back slashes as escape characters. I believe you can just add the letter 'r' just before your path. Such as sys.path.insert(0, r"D:\Projects\Python\UdemyProjects\SixSimplifying\code\models") –  Sep 21 '21 at 20:58
  • You can also change all of your backslashes to forward slashes as well. –  Sep 21 '21 at 21:00
  • I added like this one `import sys sys.path.insert(0, r"D:/Projects/Python/UdemyProjects/SixSimplifying/code/models") import user` but now I got this error: `python: can't open file 'D:\Projects\Python\UdemyProjects\SixSimplifying\code\Test.py': [Errno 2] No such file or directory` – abbas jafari Sep 22 '21 at 02:18
0

And finally, I fix my issue:

As @Little Bamboo said: I used sys concept for the import like below:

import sys    
sys.path.append("D:\\Projects\\Python\\UdemyProjects\\SixSimplifyingTwo")    
from mycode.models.userone import UserModel

But that was not all, some of my files had the same names and I changed the names of the files.

And also I had a folder called code, and from the below link I understood that code is a built-in Python module and I changed the code folder name.

Werkzeug AttributeError: 'module' object has no attribute 'InteractiveInterpreter'

abbas jafari
  • 81
  • 1
  • 9