0

I have a file structure like so.

remindMe
│
│
├───remind_me_django
│   └───listings
│           models.py
│           __init__.py
│
└───scrapy
    └───scrapy_project
        │   items.py
        │   __init__.py
        │
        └───spiders

I'm trying to import my models.py file into items.py but to no avail. When attempting to import into items.py, I get a ModuleNotFound error. Other suggestions say to add my directory to my path but that's been unsuccessful so far as well.

sys.path.append("C:\\Users\\Denze\\Projects\\remindMe\\remind_me_django\\listings")

from listings.models import Product

I've also tried:

from remind_me_django.listings import Product

The funny thing is with this import, if I right click on the import within VSCODE and go to it's definition, it opens up that modules init file, so VSCODE knows what I'm referencing but Python does not?

1 Answers1

0
root
├── remind_me_django
│   └── listings
│       └── models.py
└── run.py

models.py:

var = "the var"

run.py

import sys

sys.path.append("/Users/user/root/remind_me_django/listings")

try:
  from listings.models import var
except:
  print('here is exception')

from models import var
print("here is OK. var is", var)

sys.path.append("/Users/user/root/remind_me_django")

from listings.models import var
print("here is also OK. var is", var)

output:

here is exception
here is OK. var is the var
here is also OK. var is the var

Explanation:

After adding listings into system path python will start search for libraries inside listings directory too. What is inside listings we have? Right! Inside listings we have models.py, so we need to do from models import something

If you add remind_me_django to system path, python will check folders and files inside remind_me_django. And out library is inside listings/models.py, so we need to do from listings.models import something (or from listings import models and use it like some_variable = models.something)

But! I don't recommend to add custom system paths by using sys.path. The better practice is to do imports based on project structure

rzlvmp
  • 7,512
  • 5
  • 16
  • 45
  • Can you provide an explanation please? – Denzel Hooke Aug 20 '21 at 00:58
  • I'll try a few things and get back to you – Denzel Hooke Aug 20 '21 at 01:40
  • Did you use `/Users/user/root/...`? It is just my example path. Of course you need to add `"C:\\Users\\Denze\\Projects\\remindMe\\remind_me_django\\listings"` or `"C:\\Users\\Denze\\Projects\\remindMe\\remind_me_django"` – rzlvmp Aug 20 '21 at 01:40
  • even my example don't work? 1. Please provide full error text and contents of `models.py` 2. Try to `sys.path.append` inside head of Django's `settings.py` instead of file that using `models` – rzlvmp Aug 20 '21 at 02:59