如何使用对象类名称为不同的对象调用不同的ModelForm?
class First(models.Model):
class Second(models.Model):
class FirstForm(ModelForm):
class Meta:
model = First
class SecondForm(ModelForm):
class Meta:
model = Second
def call_form(request, my_object_id):
my_object = my_object.__class__.__name__.objects.get(pk = my_object_id)
# it should looks like below
# form = FirstForm(instance = my_object)
# or
# form = SecondForm(instance = my_object)
#
# form = my_object.__class__.__name__ .... end what then?
return render(request, 'template_name.html', {'form': form})
有人可以帮我一点吗? 非常感谢前进。
答案 0 :(得分:0)
最简单的事情可能就是创建一个将模型映射到类的字典:
form_dict = {
First: FirstForm,
Second: SecondForm,
}
def call_form(request, my_object_id):
...
form_class = form_dict[my_object.__class__]
(注意我不确定你是如何将对象传递给视图来获取类的;看起来应该是一个参数,但事实并非如此。)