我正在使用forms.ModelChoiceField
从特定模型条目中加载选项:
from order.models import Region
class CheckoutForm(forms.Form):
area = forms.ModelChoiceField(queryset=Region.objects.all(),label=("Area"))
我面临的问题是从应用程序导入类名时。我收到错误:
ImportError:无法导入名称Region
在shell中独立测试时,请注意from order.models import Region
无效。
任何想法是什么造成的?
Traceback (most recent call last):
File "/home/salma/venv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 92, in inner_run
self.validate(display_num_errors=True)
File "/home/salma/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 280, in validate
num_errors = get_validation_errors(s, app)
File "/home/salma/venv/local/lib/python2.7/site-packages/django/core/management/validation.py", line 35, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/home/salma/venv/local/lib/python2.7/site-packages/django/db/models/loading.py", line 166, in get_app_errors
self._populate()
File "/home/salma/venv/local/lib/python2.7/site-packages/django/db/models/loading.py", line 75, in _populate
self.load_app(app_name)
File "/home/salma/venv/local/lib/python2.7/site-packages/django/db/models/loading.py", line 96, in load_app
models = import_module('.models', app_name)
File "/home/salma/venv/local/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/salma/Projects/Morabiz/Saludable/saludable_django/landing/models.py", line 2, in <module>
from order.models import Dish
File "/home/salma/Projects/Morabiz/Saludable/saludable_django/order/models.py", line 4, in <module>
from order.forms import RegistrationFormNoUserName
File "/home/salma/Projects/Morabiz/Saludable/saludable_django/order/forms.py", line 7, in <module>
from order.models import Region
ImportError: cannot import name Region
答案 0 :(得分:16)
正如我在评论中提到的,表单和模型文件之间存在循环依赖关系。你要么需要重构来删除循环,要么你真的不能这样做,你必须将其中一个导入移动到使用它的函数中。