0

I have a file called views.py that imports a class from another file stored in the same folder. The other file is called models.py and the needed class is called Docgen. I'm using the following code to import.

from .models import Docgen

But I keep getting the following error. ImportError: attempted relative import with no known parent package

enter image description here

No error is shown when I write the line from .models import Docgen but it still won't work for some reason I can't figure out. For some reason the import statement isn't able to locate the file models.py.

enter image description here

I get the same error whenever I try to import a module from .models into views.py in other apps in this project as well. Could it be something in settings that has gotten changed somehow?

2 Answers2

1

You may try importing files present in the same directory as

from . import models

then change your "Docgen" references to "models.Docgen"

  • Thank you for the suggestion. That ended up with the same result. It was working previously, but the only changes made to the file were a few lines of code that have since been commented out, and the only changes to the folder it's housed in is to add additional files and folders, which I've since removed in attempt to appease the the file and make it work. I still keep getting the error. – Chad Leftwich Jul 27 '23 at 17:38
1

Have you tried this:

from your_base_directory.docgen.models import Docgen

I would also check if any init.py was maybe accidentally removed?

Martin
  • 105
  • 10
  • I think you might be right about missing __init__,py somewhere based on other things I've read related to this issue. Now to figure out where it could be missing from. I did move a couple files and folders around within the root project folder but everything that I added I've since removed in trying to resolve this issue. – Chad Leftwich Aug 03 '23 at 18:52
  • 1
    You could test this also: create a new project from scratch, add a "docgen" app to it, define the `Docgen` model, and try to import it in your views. If this time it works, you can just compare the files in the new project with the files in the original one and see what's missing or different. – Martin Aug 04 '23 at 01:16
  • Good idea. Just looking at the files I don't see anything that should be there that's missing so I'll give this a try. Thanks for the suggestion. – Chad Leftwich Aug 04 '23 at 15:06