Django tutorial: ImportError: attempted relative import with no known parent package - Stack Overflow
attempted relative import with no known parent package
-
Look into management commands. That's probably the easiest way to actually load up an instance of your server, so that you can load up the models alongside your script.
-
I'm having a bit of trouble following what you're trying to do. Normally, when creating an api, you're trying to serve something; thus is the whole point of django (it's just a series of requests/responses). Most of the time, you can use an API client (httpie, thunder, rapidapi, postman, etc.) to test the endpoints you create, however, I don't know what you have in your
client.pyfile so I don't know the context for your project scope.
apps.py: Attempted relative import with no known parent package
ImportError: attempted relative import with no known parent package : Forums : PythonAnywhere
When I have this issue on Flask or Django, I usually do my relative imports as bellow, and once debugg is complete I reset back to the normal way of doing imports with Django:
if __name__ == '__main__':
from models import Article
else:
from .models import Article
Basically depending of wether you launch your code from Python using main or from the Django server, it will select the correct way to handle your imports.
And when you want to launch your code from Python you add at the end of your code "if name == 'main':" with then your code to run:
from typing import List
# other imports
# Your article import
if __name__ == '__main__':
from models import Article
else:
from .models import Article
# Your code
def my_code_to_run():
article=Article()
# Your main
if __name__ == '__main__':
my_code_to_run()
################ IMPORTANT WHZN USING DATABASE CONNS FROM SETTINGS.PY Note that if you are calling Databases that are setup in settings.py of Django the call will not work as the connections won't be defined...
Django accepts from .models import *model_name*, but when you try to run the file as any other Python app, you'd get such an error.
to solve it, you either need to user from models import *model_name*, or run Django server python manage.py runserver
Sorry to have forgotten to post a reply to this, but the actual issue was that when working with Django, I tried to run each script on its own. Instead, with Django, you just write each script, save it, and Django automatically updates (that is, after you run the runserver command). At least, I think that's what solved the issue given my noviceness. Hope this helps the next person to encounter this issue.
Change
from . import views
to
from polls import views
-
This is probably a python problem,but i guess lot of people on this sub would have experience with this.
I have a python script 'client.py' which is supposed to fetch some data from an API,i want to save this data as my model fields .but I'm getting 'attempted relative import with no known parent package' when i try to import the models module .also if i try using an absolute import i get the 'module doesnt exist' error.
In the event of trial and error ,i also noticed that i get this error even from importing models to my views or even to admin.py, which shouldn't be a problem, since ive done this several times in my previous projects.
if i run the server, i have no problem,but the error rises when running just the script(its probably something basic that im missing i guess).
2. also is what im doing a good idea? im trying to fetch data from an api.put it into a model then serialize it again, to replicate the initial API, just to practice how to serve APIs.
is there a better way to go about it,maybe like deserializing it without using a model?i thought about that,but i just started learning django,so i dont wanna rush.
Thanks a lot
my file path
-project
-project_api
migrations
_init_.py
admin.py
apps.py
models.py
tests.py
client.py
views.py
-project
_init_.py
asgi.py
wsgi.py
settings.py
db.sqlite3
manage.py
I'm woking on a project with requires a celery worker to perform article scraping, but I'm having trouble with accessing certain models from inside the django project. Specifically, I'm thrown the error "ImportError: attempted relative import with no known parent package". Celery works as intended when I'm not trying relative imports.
Here is the tree for my project (simplified):
.
βββ celeryworker
β βββ Dockerfile
β βββ celeryconfig.py
β βββ celerytasks.py
β βββ requirements.txt
βββ newspigeon
βββ Dockerfile
βββ docker-compose
βββ home
β βββ __init__.py
β βββ admin.py
β β βββ __init__.py
β β βββ __pycache__
β βββ models.py #(TRYING TO TAKE MODELS FROM HERE!)
β βββ tasks.py
β βββ tests.py
β βββ urls.py
β βββ views.py
The error comes from the following line in celerytasks.py:
from ..newspigeon.home.models import NewsArticle, nlp_models
In my understanding, this import error is common in the python realm, but I'm wondering if there is a django-friendly fix, meaning I don't have to alter the file structure drastically or do anything with altering sys or os, which introduce other complications.
I'm wondering if anyone has experience in dealing with relative import errors in django.
Thanks and let me know if I'm being unclear/am missing key pieces of code.
It seems, from Python docs and experimenting, that relative imports (involving ., .. etc) only work if
- the importing module has a
__name__other than__main__, and further, - the
__name__of the importing module is pkg.module_name, i.e., it has to be imported from above in the directory hierarchy (to have a parent pkg as part of it's__name__.)
OR
the importing module is being specified via module syntax that includes a parent pkg as python -m pkg.module, in which case it's __name__ is still __main__, so it is being run as a script, yet relative imports will work. Here __package__ is set and used to find the parent package while __name__ is __main__; more here.
[After all that, it appears that __package__ and sys.path are key to determining if/how relative imports work. __name__ indicates script or module(i.e., __main__ or module_name). __package__ indicates where in the package the relative imports occur with respect to, and the top of __package__ needs to be in sys.path.]
So, continuing with @AmitTendulkar 's example, if you run this as > python main.py or > python -m main or > python -m ecommerce.products from the project root directory, or enter interactive python from that root directory and import main, or import ecommerce.products the relative imports in products.py will work.
But if you > python products.py or > python -m products from within ecommerce directory, or enter interactive python from that ecommerce directory and import products they will fail.
It is helpful to add
print("In module products __package__, __name__ ==", __package__, __name__)
etc. in each file to debug.
UPDATE:
How imports work depend on sys.path and __package__, not on __name__.
Issued from /home/jj, > python sub/mod.py has a sys.path, __package__ of /home/jj/sub, None -absolute imports of modules in sys.path work, relative imports fail.
> python -m sub.mod has sys.path, __package__ of /home/jj, sub -absolute imports of modules in sys.path work, relative imports work relative to sys.path + __package__.
It is more helpful to add
import sys
print("In module products sys.path[0], __package__ ==", sys.path[0], __package__)
etc. in each file to debug.
i had a similar issue on Windows, and what helped me was (adapted to your directory):
# local imports
import sys
sys.path.append(r"C:\path\to\your\project")
from ecommerce.database import Database
Hi all!
Say I have this folderstructure:
package
βββ __init__.py
βββ module.py
βββ subpackage
βββ bar.py
βββ __init__.py
βββ subsubpackage
βββ __init__.py
βββ foo.pyAnd I would like to import a function called 'func' from 'bar.py' into 'foo.py. How would I do this?
I tried literally every combination possible...like:
from .bar import func
from subpackage.bar import func
from ..bar import func
from . import bar.func
Problem is....nothing works, as I always get this error:
ImportError: attempted relative import with no known parent package
When I read on stackoverflow, I read a lot of different answers, most of them involving manipulating sys.path and quite complex.
I dont really understand why such a simple thing would be so complicated...what am I missing here?