Django - 动态导入

0 投票
4 回答
4497 浏览
提问于 2025-04-16 10:26

我正在尝试在Django中动态导入一个Python模块。我有两个不同的应用程序,想从中导入内容,并且我想替换这些导入语句:

from app1.forms import App1ProfileForm
from app2.forms import App2ProfileForm

我可以动态创建字符串App1ProfileForm和App2ProfileForm,然后像这样实例化它们:

globals()[form]()

我试着按照这个帖子中的一些说明操作:通过名称动态导入类以进行静态访问

所以我尝试了这样做:

theModule = __import__("app1.forms.App1ProfileForm")

但是我遇到了一个错误,提示没有名为App1ProfileForm的模块。

编辑:::

好的,我尝试了这段代码:

 theModule = __import__("app1")
    print theModule
    theClass = getattr(theModule,'forms')
    print theClass
    theForm = getattr(theClass,'App1ProfileForm')
    print theForm
    theForm.initialize()

但我得到一个错误,提示类型对象'App1ProfileForm'没有'initialize'这个属性。

4 个回答

1

我不太清楚你是怎么生成要导入的字符串的。我假设你是生成整个“路径”。你可以试试这个:

def import_from_strings(paths):
  ret = []
  for path in paths:
    module_name, class_name = path.rsplit('.', 1)
    module = __import__(module_name, globals(), locals(), [class_name], -1)
    ret.append(getattr(module, class_name))
  return ret
4

你不想这样做。导入模块是在相关代码第一次执行的时候进行的——对于模块级别的导入来说,就是当这个模块被导入的时候。如果你依赖于请求中的某些东西,或者其他运行时的元素来决定你需要哪个类,这样做是行不通的。

相反,直接把两个模块都导入,然后让代码来选择你需要的那个:

from app1.forms import App1ProfileForm
from app2.forms import App2ProfileForm

forms = {'app1': App1ProfileForm,
         'app2': App2ProfileForm}
relevant_form = forms[whatever_the_dependent_value_is]
0

我搞明白了。下面是怎么做的:

    theModule = __import__(module_name+".forms") # for some reason need the .forms part
    theClass = getattr(theModule,'forms')
    theForm = getattr(theClass,form_name)

然后进行初始化:

theForm() or theForm(request.POST)

撰写回答