0

So I'm working on a web-based process simulator for a steel pickling plant. I have 6 different types of forms (from 6 different Models) on the same template, which should be all submitted by the same button. Here are the models that matter to my question:

class Settings(models.Model):
    simulation = models.ForeignKey(Simulation, on_delete=models.CASCADE)
    final_time = models.IntegerField(default=3000)
    time_steps = models.IntegerField(default=50)
    film_thickness = models.FloatField(default=0.001)
    plate_thickness = models.FloatField(default=0.0005)
    plate_width = models.FloatField(default=10.0)
    number_of_pickling_tanks = models.PositiveSmallIntegerField(default=4)
    number_of_rinsing_tanks = models.PositiveSmallIntegerField(default=4)
    coil_temperature = models.FloatField(default=373.0)
    system_pressure = models.FloatField(default=100000.0)
    total_vaporization = models.FloatField(default=0.005)
    plate_velocity = models.FloatField(default=3.0)


class PicklingTank(models.Model):
    settings = models.ForeignKey(Settings, on_delete=models.CASCADE)
    number = models.PositiveSmallIntegerField()
    volume = models.FloatField(default=30)
    concentration_hcl_initial = models.FloatField(default=180.84)
    concentration_fecl2_initial = models.FloatField(default=11.35)
    concentration_fecl3_initial = models.FloatField(default=5.81)
    temperature_initial = models.FloatField(default=323.15)
    hasextinlet = models.BooleanField(default=False)

All of these are made forms as in:

class SettingsForm(forms.ModelForm):
    class Meta:
        model = Settings
        fields = '__all__'


class PicklingTankForm(forms.ModelForm):
    class Meta:
        model = PicklingTank
        fields = '__all__'

I've already done my research on how to submit several forms with one button only (django submit two different forms with one submit button), but my problem is quite different:

the number of PicklingTankForms changes dynamically depending on the value the user inputs in Settings.number_of_pickling_tanks (I am rendering one instance of the PicklingTankForm using my views.py and replicating it "on input" using JS).

So if I don't know how many PicklingTankForms the user is going to choose, how could I create one instance of PicklingTank for each PicklingTankForm when he presses Submit?

Thank you!

Kiyoshi
  • 1
  • 2

1 Answers1

0

Use formsets.

If you change your ModelForm to a Form

from django import forms
class PicklingTankForm(forms.Form):
    ...

Then you can leverage a custom number of forms with a formset

from django.forms import formset_factory
PicklingTankFormSet = formset_factory(PicklingTankForm, 
                              extra=Settings.number_of_pickling_tanks)

You can then iterate over the formset to render the forms.

formset = PicklingTankFormSet()
for form in formset:
    ... # render
arewm
  • 649
  • 3
  • 12