首页 > 解决方案 > Django:在模型导入的上下文中没有名为“foo”的模块问题

问题描述

背景信息:
我想使用atoms插件运行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实例无法正确识别它?

我试过的:

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
[...]

设置.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'
]

模型.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

项目结构:

在此处输入图像描述

标签: pythondjango

解决方案


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

更改了模型的导入路径导致模型类模型。AccountInformation 未声明显式 app_label 并且不在 INSTALLED_APPS 错误中的应用程序中

尝试在 中指定您的设置configure

from dashex import settings

settings.configure(settings)

推荐阅读