如何使用对象类名称为不同的对象调用不同的ModelForm?

时间:2015-11-16 09:23:26

标签: django django-models django-forms

如何使用对象类名称为不同的对象调用不同的ModelForm?

models.py

class First(models.Model):

class Second(models.Model):

forms.py

class FirstForm(ModelForm):
    class Meta:
        model = First

class SecondForm(ModelForm):
    class Meta:
        model = Second

views.py

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})

有人可以帮我一点吗? 非常感谢前进。

1 个答案:

答案 0 :(得分:0)

最简单的事情可能就是创建一个将模型映射到类的字典:

form_dict = {
    First: FirstForm,
    Second: SecondForm,
}

def call_form(request, my_object_id):
    ...
    form_class = form_dict[my_object.__class__]

(注意我不确定你是如何将对象传递给视图来获取类的;看起来应该是一个参数,但事实并非如此。)