0

I add a custom_site.py in my project, But I can't import it in admin.py and urls.py. I try to use sys, and use Pycharm to mark them as Sources Root, but it still can't import! It always Report an error like:

from typeidea.custom_site import custom_site
ModuleNotFoundError: No module named 'typeidea.custom_site'

Why typeidea.custom_site can't import?

My project directory and my code are here:

admin.py

from ..typeidea.custom_site import custom_site
...
@admin.register(Category, site=custom_site)

urls.py

import typeidea.custom_site

urlpatterns = [
    url(r'^super_admin/', admin.site.urls),
    url(r'^admin/', typeidea.custom_site.custom_site.urls),
]

Project:

typeidea

-blog

——admin.py ...

--comment ...

--config ...

--typeidea

——init.py

——urls.py ...

custom_site.py

ThomasXu
  • 1
  • 2
  • 1
    Don't post pictures of code. Cut-and-paste the code. Your inner files do not have any idea what the outer layers look like. You might be able to do `from ..typeidea.custom_site import custom_site` (note the double dots). – Tim Roberts Aug 21 '21 at 03:17
  • What do you mean by "I try to use sys"? You COULD do what you want by adding the root path to `sys.path`. Did you try that? – Tim Roberts Aug 21 '21 at 03:20
  • @TimRoberts I have try to use sys.path – ThomasXu Aug 21 '21 at 15:42
  • @TimRoberts My file custom_site.py is in the parent directory, I can't use so. – ThomasXu Aug 21 '21 at 15:45
  • @TimRoberts Please told me that how to use sys.path.I don't know if I am using it correctly. – ThomasXu Aug 21 '21 at 15:47
  • You can say `sys.path.append( os.path.abspath( os.path.dirname( __file__ ) + "/.." ) )` to add the current file's parent to the path. Make it `"/../.."` to add the current file's grandparent. – Tim Roberts Aug 22 '21 at 00:01
  • @TimRoberts I find that I can use `sys.path.append("..") ` to import too! Thank you so much! – ThomasXu Aug 22 '21 at 01:22
  • OK, but REMEMBER that `sys.path.append("..")` appends the parent of the CURRENT directory. If you run the script from somewhere else (`python ../../admin.py`), that won't match the script location. – Tim Roberts Aug 22 '21 at 03:30

1 Answers1

0

when you write: from X import y it imports the X module, and create reference to the y objects/methods. yours:

from typeidea.custom_site import custom_site

the typeidea.custom_site is not a module, so you cant import it.

the module that you want to use is custom_site, so just do:

import custom_site.

for more detailed explanation about it: `from ... import` vs `import .`

compete
  • 36
  • 1