Forums

import python file form a sub directory

Hi, I am trying to import a python file called myrules.py in the subdirectory rules into my views.py file. (Subdirectory in the same directory as the views.py file)

I have used;

import rules.myrules

But I get the following Error;

ModuleNotFoundError at /
No module named 'rules'
Request Method: GET
Request URL:    https://medai.pythonanywhere.com/
Django Version: 3.2.3
Exception Type: ModuleNotFoundError
Exception Value:    
No module named 'rules'
Exception Location: /home/MedAI/mysite/mysite/views.py, line 5, in <module>
Python Executable:  /usr/local/bin/uwsgi
Python Version: 3.7.10

How can I rectify this? Many thanks!

Have a look at the "Theory" section here so you can understand how Python finds the modules that you're importing.

Thanks for your suggestion. I did see this page before. I tried putting my myrules.py file in the same folder as the file (views.py) I am importing it into. Unfortunately, it still doesn't work.

I got it working by placing the file in

/home/MedAI/.local/lib/python3.7/site-packages/myrules.py

the location where all the other packages are.

Glad to hear you got that working! Just a side note -- ~/.local/lib/python3.7/site-packages/ is a location where external packages are being installed. The usual practice is to keep your code in one place, under a version control system (like git). In order to tell Python how to discover your code, you should append the path to your project to the sys.path in the WSGI file.