Depending on my models state, I want to show a different form to the user. I’m trying to figure out how I’d store a reference to the correct form so I can load it in my view.
An normal view would look like:
from myapp.forms import SomeForm
def view():
form = SomeForm()
However, since I don’t know which form my model needs, how would I dynamically import the form class?
I tried this:
from django.forms import ModelForm
modelforms = ModelForm.__subclasses__()
def get_modelform(model):
return filter(lambda x:x.Meta.model == model, modelforms)[0]
But it only works if the form has been imported into the project. Since my form lives in it’s own forms.py file, this doesn’t work 🙁
In your forms.py file, write a function that returns the correct form according to your criteria. Then import that into your view and call it there.