[Fixed]-Arbitrary amount of fields in Modelform

1👍

You are over thinking this. In database speak, a cell is the place where a column and a row intersect. You needn’t in fact you shouldn’t create a model called cell. All you need is

class Row(models.Model)
    col1 = models.SomeField()
    col2 = models.SomeField()
    col3 = models.SomeField()
    col4 = models.SomeField()
👤e4c5

0👍

I got what i needed by following code:

forms.py

class RowForm(forms.Form):
    cell = forms.CharField(label='Ячейка', max_length=100)


class RowFormSet(BaseFormSet):
    min_num = 5
    max_num = 5
    absolute_max = 5
    extra = 0
    form = RowForm
    can_order = False
    can_delete = False
    validate_max = False
    validate_min = False

    def __init__(self, *args, **kwargs):
        super(RowFormSet, self).__init__(*args, **kwargs)
        for i in range(0, NUMBER_OF_CELLS):
            self[i].fields['cell'].label += " %d" % (i + 1)

Leave a comment