I tried to import models from one app to another by using the following:
from ..appName.models import className
also
from appName.models import className
but attempted relative import beyond top-level package error occured. My aim is to create a student management system. In one app i created the model and in another app i try to retrive data from that model but failed to do it..
├───Save_to_database
│ ├───HelpingClass
│ │ └───__pycache__
│ ├───migrations
│ │ └───__pycache__
│ └───__pycache__
├───Search
│ ├───migrations
│ │ └───__pycache__
│ └───__pycache__
├───StudentApp
│ └───__pycache__
└───templates
I want to import models from save_to_database into Search.
And yes i added the app in settings.py
Excuse my english
├───Save_to_database
│ ├───HelpingClass
│ │ └───__pycache__
│ ├───migrations
│ │ └───__pycache__
│ └───__pycache__
├───Search
│ ├───migrations
│ │ └───__pycache__
│ └───__pycache__
├───StudentApp
│ └───__pycache__
└───templates
I want to import models from save_to_database into Search.
And yes i added the app in settings.py
Related
When I try to use the default docs in FastApi never works. If I use /docs it gives an error saying:
"Failed to load API definition. Error Hide Fetch Internal Server Error /openapi.json"
and if I use /redoc it loads forever and never appears anything. I searched a lot but the only thing I found out was someone using root_pah="/folder/" inside of the FastAPI() main instance, so I used the app folder which is the repository of the whole api project. I don't know if it will help you guys but the tree of the project is:
C:.
├───.pytest_cache
│ └───v
│ └───cache
├───alembic
├───app
│ ├───models
│ │ └───__pycache__
│ ├───routers
│ │ └───__pycache__
│ ├───tests
│ │ ├───.pytest_cache
│ │ │ └───v
│ │ │ └───cache
│ │ └───__pycache__
│ └───__pycache__
├───venv
│ ├───Include
│ │
│ └───Scripts
└───__pycache__
p.s. I wiped most of the part of the venv directory because I thought that it was useless for this and also when I tried to copy and paste the whole output in here, Stack Overflow would accept just part of it because it was too big.
I'm unable to add dll files using package_data in setup.py file. Here's a look at directory structure:
my_project
├── key
│ ├── 1_0
│ │ ├── sub_dir
│ │ │ ├── _required.dll
│ │ │ └── __init__.py
│ │ ├── get_key.py
│ │ └── __init__.py
│ ├── 1_1
│ │ ├── sub_dir
│ │ │ ├── _required.dll
│ │ │ └── __init__.py
│ │ ├── get_key.py
│ │ └── __init__.py
│ ├── 1_2
│ │ ├── sub_dir
│ │ │ ├── _required.dll
│ │ │ └── __init__.py
│ │ ├── get_key.py
│ │ └── __init__.py
│ └── __init__.py
├── my_program.py
└── __init__.py
I've been trying without success to add the required.dll files with the installation of this module. I know I have to add it in the setup.py file. What I've tried so far (I'll skip all unnecessary parameters) :
First:
setuptools.setup(name='my_project',
packages=setuptools.find_packages(),
include_package_data=True,
package_data={'': ['my_project\\key\\1_0\\sub_dir\\_required.dll',
'my_project\\key\\1_1\\sub_dir\\_required.dll',
'my_project\\key\\1_2\\sub_dir\\_required.dll']},
...)
Second:
setuptools.setup(name='my_project',
packages=setuptools.find_packages(),
include_package_data=True,
package_data={'key': ['1_0\\sub_dir\\_required.dll',
'1_1\\sub_dir\\_required.dll',
'1_2\\sub_dir\\_required.dll']},
...)
Third:
setuptools.setup(name='my_project',
packages=setuptools.find_packages(),
include_package_data=True,
package_data={'my_project\\key\\1_0\\sub_dir': ['_required.dll'],
'my_project\\key\\1_1\\sub_dir': ['_required.dll'],
'my_project\\key\\1_2\\sub_dir': ['_required.dll']}
...)
Whenever I call python setup.py sdist --format=zip, dll files are never included. BTW, I'd rather not change directory structure, unless there is no other option.
What am I missing here?
Regards.
François
I know this question has come up but many answers refer to older versions of Django and Python. I am running Django 3 and Python 3.
Besides in our project we have decided to separate each model in its own file under a "models" folder. Please see below our tree structure:
├── db.sqlite3
├── manage.py
├── poi
│ ├── admin.py
│ ├── apps.py
│ ├── CHANGELOG.md
│ ├── fabfile.py
│ ├── __init__.py
│ ├── LICENSE
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── 0002_auto_20210104_1048.py
│ │ ├── __init__.py
│ │ └── __pycache__
│ │ ├── 0001_initial.cpython-38.pyc
│ │ ├── 0002_auto_20210104_1048.cpython-38.pyc
│ │ └── __init__.cpython-38.pyc
│ ├── models
│ │ ├── __init__.py
│ │ ├── layer.py
│ │ ├── poi.py
│ │ ├── __pycache__
│ │ │ ├── __init__.cpython-38.pyc
│ │ │ ├── layer.cpython-38.pyc
│ │ │ ├── poi.cpython-38.pyc
│ │ │ └── tag.cpython-38.pyc
│ │ └── tag.py
│ ├── models.py
In our models/init.py we have:
from .poi import Poi
from .tag import Tag
from .layer import Layer
In our models/poi/poi.py we have:
from django.db import models
from .tag import Tag
from .layer import Layer
class Poi(models.Model):
...
...
tags = models.ManyToManyField('Tag', through='Layer')
def __str__(self):
return self.name
In our models/poi/tag.py we have:
from django.db import models
import poi.models.poi
import poi.models.layer
class Tag(models.Model):
name = models.CharField(max_length=100)
pois = models.ManyToManyField('Poi', through='Layer')
def __str__(self):
return self.name
In our models/poi/layer.py we have:
from django.db import models
import poi.models.poi
import poi.models.tag
class Layer(models.Model):
poi = models.ForeignKey(Poi, on_delete=models.CASCADE)
tag = models.ForeignKey(Tag, on_delete=models.CASCADE)
The error comes up when we run python3 manage.py makemigrations.
Error:
File "/media/elena/DATA2/Python-projects/osm-pois/osm-pois/upoi/poi/models/layer.py", line 8, in Layer
poi = models.ForeignKey(Poi, on_delete=models.CASCADE)
NameError: name 'Poi' is not defined
We have tried other ways of import in layer.py such as:
from .poi import Poi
from .tag import Tag
But that gave us the following error:
File "/media/elena/DATA2/Python-projects/osm-pois/osm-pois/upoi/poi/models/layer.py", line 2, in <module>
from .poi import Poi
ImportError: cannot import name 'Poi' from partially initialized module 'poi.models.poi' (most likely due to a circular import) (/media/elena/DATA2/Python-projects/osm-pois/osm-pois/upoi/poi/models/poi.py)
Any idea of how to solve this? Thanks!
I am posting as an answer what #TonySuffolk66 suggested via a comment since it worked perfectly. Thanks again!
Because your models are defined in different files, try doing this : poi = models.ForeignKey('Poi', on_delete=models.CASCADE) That is using a string for the model name, not a reference name. You can't 'easily' import other models like this due to the way that Django initializes
I have an existing project (let's name it main) on Django and several applications in it. There is a separate project, also in django, and one application inside it (we will call this the second one). Here is a generalized file structure for project "second":
my_second_project
│ manage.py
│ models.py
│ my_models.py
│ my_views.py
│
├───myapp
│ │ admin.py
│ │ apps.py
│ │ Funcs.py
│ │ models.py
│ │ tests.py
│ │ urls.py <-- from here urls import to project urls file
│ │ views.py
│ │ __init__.py
│ │
│ ├───migrations
│ │ └───...│
├───my_second_project
│ │ asgi.py
│ │ settings.py
│ │ urls.py <-- HERE all urls i need
│ │ wsgi.py
│ │ __init__.py
├───templates
│ ...
│
└───__pycache__
models.cpython-37.pyc
Here is a generalized file structure for project "main":
main_project
├───app ...
│ ├───...
├───main_project
│ ├───media
│ │ └───user_uploads
│ ├───settings
│ │ └───base.py
│ └───urls.py
├───app ...
│ ├───...
├───app ...
│ ├───...
└───static
├...
I need to integrate "second" project into my existing one (main project), ideally without making any changes to the second project. I tried to do it in the same way that applications are integrated (via urls include), but it seems that it does not work with projects because django writes "myapp module not found".
url('data-classifier/', include('my_second_project.my_second_project.urls'))
Is there some way to add a "second" project to my "main" project without changing the "second" one?
When you deploy these projects they won't be stored in directories nearby. Ideally they won't be on the same server at all.
Instead if you can't afford to copy (or move) contents of the app you need from second to main project, and you don't want to redirect with nginx, make a small app in your main project and from urls.py redirect to endpoints of second.
main_project.my_second_project.urls.py
from django.urls import path
from django.views.generic import RedirectView
app_name = 'my_second_project'
urlpatterns = [
path('endpoint/', RedirectView.as_view(url='<my_second_project_url>'), name='endpoint')
]
If you're running main locally at 8000, and second at 8001, then you'd put 'http://localhost:8001/endpoint/' as url up there.
I have the following directory structure in my home projects folder.
|ALL-IN-ONE
|demo
|__init__.py
|__main__.py
|models
|grpc
|allinone_server.py
And I want to import from allinone_server.py a function defined in main.py called images_demo. I have tried
from demo.__main__ import images_demo
It is not working. How can I import it? The function I am trying to import is located inside main.py which is inside demo directory. I am trying to import it from the file allinone_server.py in grpc. I guess I have made my question clear now.
Here is the whole tree for the project
├── demo
│ ├── __init__.py
│ ├── __main__.py
│ └── __pycache__
│ ├── __init__.cpython-36.pyc
│ └── main.cpython-36.pyc
├── description
├── environment.yml
├── HEAD
├── hooks
│ ├── applypatch-msg.sample
│ ├── commit-msg.sample
│ ├── fsmonitor-watchman.sample
│ ├── post-update.sample
│ ├── pre-applypatch.sample
│ ├── pre-commit.sample
│ ├── prepare-commit-msg.sample
│ ├── pre-push.sample
│ ├── pre-rebase.sample
│ ├── pre-receive.sample
│ └── update.sample
├── imgs
│ └── 44.jpg
├── info
│ └── exclude
├── __init__.py
├── loggers
│ ├── __init__.py
│ └── __pycache__
│ └── __init__.cpython-36.pyc
├── models
│ ├── adience_large1.h5
│ ├── adience_small1.h5
│ ├── AgeModel.json
│ ├── detection_age_gender_large1.h5
│ ├── detection_age_gender_small1.h5
│ ├── detection_age_gender_smile_large1.h5
│ ├── detection_age_gender_smile_small1.h5
│ ├── detection_age_large1.h5
│ ├── detection_age_small1.h5
│ ├── detection_large1.h5
│ ├── detection_small1.h5
│ ├── grpc
│ │ ├── adele_2016.jpg
│ │ ├── allinone_client.py
│ │ ├── all_in_one_pb2_grpc.py
│ │ ├── all_in_one_pb2.py
│ │ ├── all_in_one.proto
│ │ ├── allinone_server.py
│ │ ├── benedict_cumberbatch_2014.png
│ │ ├── cat.png
│ │ ├── classroom_in_tanzania.jpg
│ │ ├── decoded1.py
│ │ ├── decoded.py
│ │ ├── elon_musk_2015.jpg
│ │ ├── laos.jpg
│ │ ├── model_face.jpg
│ │ ├── __pycache__
│ │ │ ├── all_in_one_pb2.cpython-36.pyc
│ │ │ ├── all_in_one_pb2_grpc.cpython-36.pyc
│ │ │ └── decoded.cpython-36.pyc
│ │ ├── sophia.jpg
│ │ ├── test
│ │ │ ├── __init__.py
│ │ │ ├── __pycache__
│ │ │ │ └── __init__.cpython-36.pyc
│ │ │ └── test_images
│ │ │ ├── adele_2016.jpg
│ │ │ ├── benedict_cumberbatch_2014.png
│ │ │ ├── classroom_in_tanzania.jpg
│ │ │ ├── elon_musk_2015.jpg
│ │ │ ├── __init__.py
│ │ │ ├── laos.jpg
│ │ │ ├── model_face.jpg
│ │ │ ├── sophia.jpg
│ │ │ ├── waaah.jpg
│ │ │ ├── woman.jpg
│ │ │ └── zebra_stripes.jpg
│ │ ├── waaah.jpg
│ │ ├── woman.jpg
│ │ └── zebra_stripes.jpg
So you've referred to main.py, but you also have __main__.py in your directory structure. I'll assume that your directory actually contains main.py instead of __main__.py.
To import from levels up in a package, start your import with a period.
To import just one function you would use from .main import images_demo
Now, let's start by saying main.py is in grpc/ along with allinone_server.py, then we'll move it to different directories and see how the import changes.
If it were in grpc/ from .main import images_demo
If it were in models/ from ..main import images_demo
If it were in __ALL-IN-ONE/ from ...main import images_demo
If it were in __demo/ from ...__demo.main import images_demo
Every extra period brings you up one level in the hierarchy, then you use the name of the next level down in the target path until you reach where you want to be.
Now let's suppose you wanted to import the whole of main.py.
If it were in grpc/ from . import main
If it were in models/ from .. import main
If it were in __ALL-IN-One/ from ... import main
If it were in __demo/ from ...__demo import main
Finally, the dot notation to move up a level only works if the file that uses it is in a package, so this will work fine if at the top level you start your program in a scope outside of this package then use from __ALL-IN-ONE.models.grpc import allinone_server
However, if you run allinone_server.py directly then it will fail to import anything above it as it isn't being imported as part of a package. Try that out, and let me know if that needs better explanation.
Good luck!
You can't import a function from another folder directly and for that you have to use this:
import sys
sys.path.insert(0, "../../demo/")
Another step is to rename __main__ to main.
here is the exact example that worked for me:
The tree:
.
├── demo
│ ├── __init__.py
│ ├── main.py
│
└── models
└── grpc
└── allinone_server.py
main.py:
def images_demo():
print("hello there")
The calling file(allinone_server.py):
import sys
sys.path.insert(0, "../../demo/")
import main
main.images_demo()