2011-01-22 5 views
0

나는 django에서 파이썬 모듈을 동적으로 가져 오려고합니다. 나는에서 가져올 두 개의 서로 다른 애플 리케이션을 가지고 있고, 나는이 import 문 교체하려면 :Django - 동적으로 가져 오기

globals()[form]() 
: 나는 문자열 App1ProfileForm 및 App2ProfileForm를 만든 다음과 같이 그것들을 초기화 할 동적으로 수 있어요

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

나는이 게시물의 지침 몇 가지 다음과 같은 시도 : Dynamically import class by name for static access

하고하는 것은 그래서 나는이 일을 시도 :

,651,

하지만 난 App1ProfileForm 이름

편집 ::: 이 코드 시도 확인 없음 모듈 말한다 오류 받고 있어요 :

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

을하지만 오류가 해당 유형의 객체 App1ProfileForm '을 '초기화'속성이 없습니다.

+0

는'theForm'는 클래스입니다. 그걸 사용하지 않고 인스턴스화하고 싶습니다. 'theForm(). initialize()'와 같은 것을 시도해보십시오. – pkoch

답변

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) 
+0

아, 작동하지 않습니다. 일단 가져 오기를 꺼내면 – JPC

+0

이 작동합니다. 왜 .forms 부분이 필요한지 잘 모르겠습니다. – JPC

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 
+0

여기서 'paths'는 어디에 정의되어 있습니까? – kelloti

+0

함수의 인수입니다. 아니? import_from_strings ([readline.get_history_length ','readline.get_line_buffer '])으로 테스트했습니다. – pkoch

+0

이 내 게시물을 편집했습니다. – JPC

1

모듈이 아닌 클래스를 가져 오시겠습니까? 전문가는 아니지만 __import__을 사용하여 모듈을 가져와야하고 yourmodule.App1ProfileForm과 같은 App1ProfileForm 클래스를 선택해야한다고 생각합니다.

+0

이것은 닫습니다. 새로운 시도를 표시하기 위해 내 게시물을 편집했습니다. – JPC

3

이 작업을 원하지 않습니다. 가져 오기는 관련 코드가 처음 실행될 때 수행됩니다. 모듈 수준 가져 오기의 경우 모듈 자체를 가져올 때입니다. 요청한 클래스 또는 다른 런타임 요소에 의존하여 원하는 클래스를 결정하는 경우에는 작동하지 않습니다.

대신에, 당신이 필요로하는 하나를 선택하는 코드를 둘 다 가져올 수 :

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

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

더 적은 마법이 더 좋습니다 . – pkoch

+0

나는 앱을 더 재사용 할 수 있도록 노력하고있다. 이 프로젝트를 다른 프로젝트에서 사용하려고하면 가져 오기를 변경해야합니다. 재사용 성은 목표로 삼을 것이 아닌가? – JPC

관련 문제