简体   繁体   English

Django检视ImportError

[英]Django views ImportError

I don't know if this logic is correct, I'm trying to import a Django view in 2 different views. 我不知道这种逻辑是否正确,我正在尝试以2个不同的视图导入Django视图。 I have an import chain like this: 我有一个这样的导入链:

the

a.views import b.views
b.views import c.views
c.views import d.views

and

d.views import b.views

but when I reach the last step I get an ImportError . 但是当我到达最后一步时,我得到一个ImportError

If I put a comment in d.views avoiding the import of b.views , it works. 如果我在d.viewsd.views评论以避免导入b.views ,则它可以工作。

I'm new with Django, can somebody help me? 我是Django的新手,有人可以帮助我吗?

If I use in a.views and in d.views the syntax 如果我在a.viewsd.views使用语法

from b.views import *

it works, but.. the code is not so readable. 它可以工作,但是代码不是那么可读。

If I use 如果我用

from b.views import my_func

it doesn't work! 它不起作用!

This is the error from django shell: 这是django shell的错误:

>>> import maps.views
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/save/sites/myblog/maps/views.py", line 19, in <module>
    from places.views import *
  File "/Users/save/sites/myblog/places/views.py", line 22, in <module>
    from posts.views import *
  File "/Users/save/sites/myblog/posts/views.py", line 31, in <module>
    from maps.views import render_map_geoloc
ImportError: cannot import name render_map_geoloc

Its because of cyclic dependency or circular reference. 这是因为循环依赖或循环引用。

b depends on c
c depends on d
d depends on b #which depends on c

Not sure for what purpose you are using. 不知道您使用什么目的。 But you do explicit import to that function, and right above where its been used. 但是,您确实要对该函数进行显式导入,并且在使用该函数的上方。

Looking at the error you are getting, it might be because of some dependency expected for d is coming from b so if you from b.views import * , it gets you that dependency. 查看您得到的错误,可能是因为预期d的某些依赖项来自b,所以如果您from b.views import * ,它将获得该依赖项。 But if you import specific view ( my_func ), its missing that dependency. 但是,如果您导入特定的视图( my_func ),它将丢失该依赖项。

Some more details you can find on SO answer thread - Django App Dependency Cycle 您可以在SO回答线程上找到更多详细信息-Django应用程序依赖周期

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM