TransWikia.com

Django tabular input form (user can key in data into table)

Stack Overflow Asked by Eka Buyung Lienadi on January 11, 2021

I attempt to create a tabular input form. User can key in data into the table cells. The table should have 100 rows. The following is an illustration of the end goal.

sample table

However, if such table is not possible, a suggestion to create the following table is also welcomed!
sample table 2

This is what I have tried:

forms.py

class SampleInputForm(forms.Form):
    x = forms.FloatField()
    y = forms.FloatField()

views.py

class ToolView(View):
    def get(self, request):

        table_rows = 10
        sample_form_set_factory = formset_factory(SampleInputForm, extra = table_rows)
        sample_form_set = sample_form_set_factory()

        context = {
            'sample_form' : sample_form_set,
        }
        return render(request, 'tools/tools.html', context)

html file

{% csrf_token %}
<form method="post">
    <table>
        <tr>
            <th>Input</th>
            <th>Output</th>
        </tr>
        {{sample_form}}
    </table>
</form>

However, this attempt does not form a table. The Y input field is displayed below the X, hence not forming a table.

One Answer

formset_factory is iterable , so in template you can do this

<form method="post">
    <table>
        <thead>
            <tr>
                <th>Input</th>
                <th>Output</th>
            </tr>
        </thead>
        <tbody>
            {% for form in sample_form %}
            <tr>
                <th>
                    {{ form.x }}
                </th>
                <th>
                    {{ form.y }}
                </th>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</form>

Correct answer by rgermain on January 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP