Importing from a package using Django as an ORM gives a ModuleNotFoundError

Versions:

  • Django 2.0.3
  • Python3.6.3

I have a package (mypkg) that uses django as an ORM.

I want to use this package in a client script (client / myclient / main.py).

I was able to use Django ORM directly in the client application - the problem is when I want to use it inside a package that is used by several client applications.

The package code is as follows:

# ./mypkg_wrapper/mypkg/mypkg/settings.py INSTALLED_APPS = [ 'django.contrib.contenttypes', 'myapp', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } SECRET_KEY = '...' # mypkg/myapp/models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=200) # mypkg_wrapper/setup.py #!/usr/bin/env python import os from setuptools import find_packages, setup # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='mypkg', version='0.0.1', packages=find_packages(), include_package_data=True, description='A django ORM package.', install_requires=['django', 'pytz'] ) 

I ran makemigrations, migrated to set up the database.

I ran python setup.py sdist which created mypkg_wrapper/dist/mypkg-0.0.1.tar.gz

Client Code:

 # myclient/settings.py INSTALLED_APPS = [ 'django.contrib.contenttypes', 'mypkg.myapp', ] SECRET_KEY = '...' # myclient/main.py if __name__ == '__main__': import os from os.path import abspath, dirname, join import sys import django sys.path.append(join(abspath(dirname(__file__)), '..')) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') django.setup() import mypkg.myapp 

In the venv client, I ran pip install ../mypkg_wrapper/mypkg-0.0.1.tar.gz , which seems to have successfully installed the mypkg package.

Then I tried to run python myclient/main.py , and when I tried to import mypkg.myapp, I got the following error.

ModuleNotFoundError: No module named 'mypkg'

The mypkg package is in the venv client:

 $ pip list Django (2.0.3) mypkg (0.0.1) pip (9.0.1) pytz (2018.3) setuptools (28.8.0) 

I saw similar questions here, but none of the answers raised this issue.

I tried / reviewed a few things:

  • import mypkg in main.py - same error
  • mypkg instead of mypkg.myapp in the INSTALLED_APPS client - same error
  • Not sure if I need to create a database in every client? How will the database work across multiple package clients?
+5
source share
1 answer

Have you checked if your application will appear in the venv installed packages folder? It should be something like

 .../venv/lib/python3.5/site-packages 

If he checks the files there to see if there is anything strange. If it is not there, the package has not been installed.

EDIT: Your Python folder may be 3.6

0
source

Source: https://habr.com/ru/post/1275744/


All Articles