Apostolos
Apostolos

Reputation: 8101

create model formsets from same model but with different model forms

I have an Image model in my Django project. Because of different types of Image I have created three ModelForms according to each type:

class Xray(ModelForm):
    #extra_field: Choice Field with specific options for Xray
    class Meta:
        model = Image

class Internal(ModelForm):
    #extra_field: Choice Field with specific options for Internal
    class Meta:
        model = Image

class External(ModelForm):
    #extra_field: Choice Field with specific options for External
    class Meta:
        model = Image

Each ModelForm has a save logic implemented. I want to create a model formset one for each Image type but want to use the correct ModelForm for each type of Image. I won't use this formset for editing thus I always want it to be empty and have 5 forms(5 items). I can't seem to find in django docs where i can use a specific form for a formset. Only a specific formset (inherit from BaseModelFormSet)

Is it possible to use specific form for each model_formset?

Upvotes: 0

Views: 262

Answers (1)

orokusaki
orokusaki

Reputation: 57128

You can do the following:

from django.forms.models import modelformset_factory

from someproject.someapp.models import Image
from someproject.someapp.forms import Internal


ImageFormSet = modelformset_factory(Image, form=Internal)

Here are the docs for modelform_factory, which don't mention the form argument. However, in the "Note" below the examples therein that the function delegates to formset_factory, which is documented to take the form argument. It's just a minor docs issue, and might be a good reason to create a fork of Django, make an update to the docs, and create a pull request.

Upvotes: 1

Related Questions