1๐
โ
You could use a Factory pattern for this. Use HumanModel.__name__
to refer to the name of the class in the selection, than use the name in the Factory to create concrete instances of the class.
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)
๐คdotcs
Source:stackexchange.com