djangoformsdjango-formscontenttype

DJANGO - How to generate a form for a model not known in advance because of the contentType instance


I have the following model and it's form:

class Project(models.Model)

class ProjectForm(forms.ModelForm)
    class Meta:
        Model = Project

So it's easy to create a form by instantiating:

form = ProjectForm()

But in my case, I have several models aside from "Projects", and I don't know in advance for which of these models I will need to create the form.

So I would like to create the form from the ContentType instance of the Project model.

In other words, I'm looking for something that looks like:

myproject = Project()
form = createform(myproject.ContentType)

Solution

  • Presumably you have a certain limited selection of models that might be used. The simplest way is just to create form classes for each of them, then choose the one you need from a dictionary:

    MODEL_FORMS = {
        MyModel: MyModelForm,
        MyOtherModel: MyOtherModelForm
    }
    
    my_form_class = MODEL_FORMS[my_project.content_type]
    my_form = my_form_class()