Django形式:在Meta中动态定义模型

时间:2012-05-28 09:32:39

标签: python django django-models django-forms

我有以下表格:

class EmailPreferences(forms.ModelForm):
    """ Base form used for fields that are always required """
    def __init__(self, *args, **kw):
        super(EmailPreferences, self).__init__(*args, **kw)

    class Meta:
        model = teacher_email_preferences
        exclude = ['id', 'c_user']

    def save(self, force_insert=False, force_update=False, commit=True):
        obj = super(EmailPreferences, self).save(commit=commit)
        return obj

正如您所见,模型名称已修复,即teacher_email_preferences。但我的网站有两种类型的用户,一种是Teacher,另一种是Student。我不想创建一个单独的表单。所以我想在启动此表单时将模型更改为student_email_preferences。在执行form = EmailPreferences()时如何在此处传递模型?

1 个答案:

答案 0 :(得分:1)

你做不到。但你可以改用闭包。

def emailform(emailmodel):
    class EmailPreferences(forms.ModelForm):
         ...

        class Meta:
            model = emailmodel

         ...

    return EmailPreferences

 ...

form = emailform(teacher_email_preferences)()