在ModelForm中重写Meta [英] Override Meta in ModelForm

查看:142
本文介绍了在ModelForm中重写Meta的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有:

class MCQuestionForm(forms.ModelForm):
    class Meta:
        model = models.MultipleChoiceQuestion
        fields = ('prompt',)

我可以覆盖 class Meta 模型更改为其他模型?例如:

Can I override class Meta to change model to some other model? For instance:

class Meta:
    model = models.EssayQuestion

编辑:

我必须补充一点,我需要在运行时进行此覆盖,模型类将来自视图逻辑中的结果

I had to add that I need to make this override at runtime, the model class will come from the result in views' logic

推荐答案

您的意思是在运行时吗?是的你可以。这是一种简单的方法:

Do you mean at runtime? Yes, you can. Here is a simple way to do it:

def get_question_form(conditional_model):
    class MCQuestionForm(forms.ModelForm):
        class Meta:
            model = conditional_model
            ...
    return MCQuestionForm

然后在您的视图中,您可以覆盖 get_form_class 方法,并使用该函数返回带有所需模型的类。

Then in your view, you can override the get_form_class method and use that function to return the class with whatever model you want on it.

如果您使用的是基于函数的视图,则可能看起来像这样:

If you're using function-based views, it might look something like this:

def my_view(request):
    model = MultipleChoiceQuestion
    if some_condition:
        model = EssayQuestion
    form = get_question_form(model)
    # now do stuff with form...

如果您使用的是基于类的视图,则可能看起来像这样:

If you're using class-based views, it might look something like this:

from django.views.generic import FormView

class MyView(FormView):
    ...
    def get_form_class(self):
        model = MultipleChoiceQuestion
        if some_condition:
            model = EssayQuestion
        return get_question_form(model)
    ...

这篇关于在ModelForm中重写Meta的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆