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=(...), )
- [Django]-Inheritance model update to its parent model
- [Django]-How do you decide on creating a new model vs a field in django?
Source:stackexchange.com