SaidAkh SaidAkh - 7 days ago 6
Python Question

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

Answer

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