0

I am running the project and shows this error. I have googled and tried some of the solutions but doesn't seem to work.

File "/home/bs-094/Dev/backend/busgroup-backend/src/bus_portal_backend/apps/inquiry/forms/inquiry_details.py", line 2, in <module>
    from ..models.inquiry import Inquiry
ValueError: attempted relative import beyond top-level package

My folder structure is

busgroup-backend
 src
  bus_portal_backend
   apps
    inquiry
      models
       _init_.py
       inquiry.py
      forms
       inquiry_details.py

It would be great help is anyone helps me solve the problem. I am fairly new to django. Thanks

EDIT: Here's what solved my problem, I had to import in this way

from bus_portal_backend.apps.inquiry.models import Inquiry

Also, I was running with debugger. My script path was busgroup-backend/src/manage.py, I changed it to /home/bs-094/Dev/backend/busgroup-backend/src/manage.py, which made me run the project successfully.

Proteeti Prova
  • 1,079
  • 4
  • 25
  • 49

2 Answers2

1

forms does not appear to contain an __init__.py file, and so Python doesn't think it's a package. Therefore an attempt to import from ..models is an attempt to ascend above the current package's root (because ...busgroup-backend/src/bus_portal_backend/apps/inquiry/forms/inquiry_details.py is actually a standalone module).

Relative imports only work within a package. Therefore you should make both forms and models subpackages of inquiry by creating inquiry__init__.py as well.

holdenweb
  • 33,305
  • 7
  • 57
  • 77
  • So shall I make another `__init__.py` inside `forms`? My models/__init__.py has `from .inquiry import *` inside it. – Proteeti Prova Jul 02 '19 at 10:14
  • I think you'll need both, but you won't break anything by experimenting. Be bold! – holdenweb Jul 02 '19 at 10:20
  • Can you explain me where do I create `inquiry__init__.py` and what do I write inside it? Creating __init__.py inside forms doesn't solve the problem. – Proteeti Prova Jul 02 '19 at 10:24
  • 1
    No. there's plenty of reference material. Start at [the documentation](https://docs.python.org/3/tutorial/modules.html#packages) and ask specific questions if there are things you don't understand. – holdenweb Jul 02 '19 at 10:50
  • 1
    This wasn't meant to be unkind, by the way, but to ensure you got the information you needed. You may also find [this answer](https://stackoverflow.com/a/24303380/146073) helpful! – holdenweb Jul 03 '19 at 13:38
  • sorry my EDIT portion somehow didn't get posted, my bad. Updating it now. – Proteeti Prova Jul 03 '19 at 13:48
1

If you import from ..models.inquiry import Inquiry then .. refers to

busgroup-backend
 src
  bus_portal_backend
   apps

Which does not have an __init__.py and thusly is not considered a package by python.

Richard Neumann
  • 2,986
  • 2
  • 25
  • 50