Carl Brubaker
Carl Brubaker

Reputation: 1655

Django: Reuse ModelForm with different Models

I am trying to make a schedule with different responsibilities. I want to order the participants for a rotation, like:

  1. Participant 12
  2. Participant 4
  3. etc...

I was going to save each responsibility order in a different model. Since my ModelForm is the same for each responsibility, is it possible to change the model being used when the form is instantiated?

class ReusableModelForm(ModelForm):

    class Meta:
        model = desired_model


# Call it like this
ReusableModelForm(data, desired_model=MyModel_1)

ReusableModelForm(data, desired_model=MyModel_2)

Upvotes: 0

Views: 267

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

Django alreaady has such functionality: the modelform_factory(..) [Django-doc]. This function is used to create forms in a CreateView for example.

You can thus construct a form class with:

from django.forms import modelform_factory

MyModel_1Form = modelform_factory(MyModel_1, fields='__all__')

You can for example subclass with:

class MyModel_1Form(modelform_factory(MyModel_1, fields='__all__')):
    class Meta:
        labels = {
            'some_field': 'some_label',
        }

Then later you can thus construct a form instance with MyModel_1Form(). The MyModel_1Form inherits from ModelForm [Django-doc].

We can use this to construct ad hoc forms and for example pass data to it like:

def modelform_init(model, *args, fields='__all__', **kwargs):
    return modelform_factory(model, fields=fields)(*args, **kwargs)

We can then, if you do not want to customize, construct a ModelForm instance, with:

modelform_init(MyModel_1, request.POST)

Upvotes: 2

Related Questions