Django:在模型导入的上下文中没有名为“ foo”的模块问题

时间:2019-12-03 12:16:12

标签: python django

背景信息:
我想使用原子feeder.py插件运行script脚本。我第一个遇到一个ImproperlyConfigured错误,该错误已按照此处的建议解决:First fix

然后我遇到RuntimeError: Model class models.AccountInformation doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.错误,该错误通过使用模型导入的绝对路径来解决,如下所示。

当前问题:
使用提到的绝对导入,我收到此错误:

ModuleNotFoundError: No module named 'Dashboard_app'

我什至可以为该应用程序等渲染模板。所以我很困惑,为什么他告诉我该模块不存在。当我删除模型导入时,一切正常。可能script实例无法正确识别它吗?

我尝试过的事情:

  • 删除并重新创建的__init__.py
  • 检查了要包含在INSTALLED-APPS dic中的应用设置
  • 将导入路径更改为DASHEX.Dashboard_app.models,导致出现no module named DASHEX错误
  • 将导入路径更改为models,导致出现Model class models.AccountInformation doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS错误
  • INSTALLED_APPS中的应用更改为Dashboard_app

feeder.py脚本:

import django
from django.conf import settings
import zmq
import time
from time import sleep
import uuid
settings.configure()
django.setup()
import sys
print(sys.path)
from Dashboard_app.models import AccountInformation
[...]

settings.py:

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    #other Apps
    'Wiki_app',
    'rest_framework',
    'Dashboard_app.apps.DashboardAppConfig'
]

Models.py:

from django.db import models
import uuid

# Create your models here.


class AccountInformation(models.Model):
    version = models.CharField(max_length=20, blank=False)
    DID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    accountNumber = models.IntegerField(blank=False)
    broker = models.CharField(max_length=50, blank=False)
    leverage = models.CharField(max_length=10, blank=False)
    account_balance = models.FloatField(max_length=15, blank=False)
    account_profit = models.FloatField(max_length=15, blank=False)
    account_equity = models.FloatField(max_length=15, blank=False)
    account_margin = models.FloatField(max_length=15, blank=False)
    account_margin_free = models.FloatField(max_length=15, blank=False)
    account_margin_leve = models.FloatField(max_length=15, blank=False)
    account_currency = models.CharField(max_length=20, blank=False)

    class Meta:
        db_table = 'AccountInfo'

    def __str__(self):
        return self.accountNumber

项目结构:

enter image description here

1 个答案:

答案 0 :(得分:1)

我认为(几乎可以肯定!)问题出在settings.configure()上;由于您没有指定任何default_settings,因此django将使用它的默认设置模板(创建新项目时会看到的模板),而Dashboard_app则不存在。这就是造成此错误的原因:

  

更改了模型的导入路径,从而生成了Model类模型。AccountInformation未声明显式的app_label,也未在应用程序中出现INSTALLED_APPS错误

尝试在configure中指定设置:

from dashex import settings

settings.configure(settings)