mr_bulrathi
mr_bulrathi

Reputation: 554

Arbitrary amount of fields in Modelform

At first let me excuse for my English, it's not my native language.

I need to construct a table of, say, 1000 rows and 5 cells in each row, so i've decided to have Cell and Row models.

models.py

class Cell(models.Model):
    content = models.CharField(max_length=100)
    row = models.ForeignKey('Row')

class Row(models.Model):
    pass

The contents of the table cells is unimportant (at the current stage i'm filling it with random data).

What i need is to be able to add a new rows. The form should have an input field (it's nature is absolutely inconsiderable) in each cell. I prefer to use a Modelform:

forms.py

class RowForm(forms.ModelForm):
    class Meta:
        model = Row
        fields = ??? <- problem here.

How can i get a Modelform that supplies input fields for each cell (keeping in mind that the amount of the cells may change in future)? I hope i've expressed my needs quite clearly. Thanks a lot!

Upvotes: 0

Views: 32

Answers (2)

mr_bulrathi
mr_bulrathi

Reputation: 554

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)

Upvotes: 0

e4c5
e4c5

Reputation: 53774

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()

Upvotes: 1

Related Questions