有没有选择做这样的事情: - 我有一节课:
class SelectForm(forms.Form):
selection = forms.ChoiceField(
choices=[
(HumanModel, 'Human'),
(OtherHumanModel, 'Other Human')
]
)
等
我有一张表格:
def MyView(request):
if request.method == "GET":
form = SelectForm()
return render(request, 'some-html', {
"form": form
})
if request.method == "POST":
data = request.POST['selection']
#make a instance?
return render(...)
在我看来:
content div
并且例如在数据中是HumanModel,但是在unicode中 有可能制作这个模型的实例吗? object = data(name =“John”)???
答案 0 :(得分:1)
您可以使用工厂模式。使用HumanModel.__name__
来引用选择中的类的名称,而不是使用Factory中的名称来创建类的具体实例。
class SelectForm(forms.Form):
selection = forms.ChoiceField(
choices=[
(HumanModel.__name__, 'Human'),
(OtherHumanModel.__name__, 'Other Human')
]
)
class HumanModelFactory(object):
def __init__(self, model_name):
if model_name == "HumanModel":
return HumanModel()
if model_name == "OtherHumanModel":
return OtherHumanModel()
# usage
model_name = request.POST['selection'] # e.g. 'HumanModel'
instance = HumanModelFactory(model_name)