SaidAkh
SaidAkh

Reputation: 1861

Override Meta in ModelForm

If I have:

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

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

class Meta:
    model = models.EssayQuestion

EDIT:

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

Upvotes: 3

Views: 3339

Answers (3)

Sardorbek Imomaliev
Sardorbek Imomaliev

Reputation: 15380

I think you are looking for modelform_factory https://docs.djangoproject.com/en/1.10/ref/forms/models/#modelform-factory

from django.forms.models import modelform_factory

if condition:
    model = models.MultipleChoiceQuestion
else:
    model = models.EssayQuestion

runtimeform_class = modelform_factory(model, fields=(...), )

Upvotes: 1

denvaar
denvaar

Reputation: 2214

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

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

Upvotes: 4

AKS
AKS

Reputation: 19811

Yes, you can. Have a look at Form Inheritance in django documentation.

You can create a new form for EssayQuestion and inherit MCQuestionForm.Meta in Meta inner class:

class EssayQuestionForm(MCQuestionForm):

    class Meta(MCQuestionForm.Meta):
        model = models.EssayQuestion

Upvotes: 1

Related Questions