[Django]-Override Meta in ModelForm

4πŸ‘

βœ…

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)
    ...
πŸ‘€denvaar

1πŸ‘

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
πŸ‘€AKS

1πŸ‘

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=(...), )

Leave a comment