如何在表单数组中获取单个表单数据

时间:2019-01-13 13:42:59

标签: python html django

所以我有一个表单数组,并将其传递给html,它起作用了。但是我在获取数据时遇到问题。如何从表单数组获取数据?在当前状态下,我只能从数组的最后一个表单中获取数据。

我想使用表单集,但我不知道如何将item.name和item.stock传递给单个表单。

forms.py:

class ItemStockChangeForm(forms.Form):
    name = ''
    stock = 0
    choices = [('add', 'Add'), ('sub', 'Sub')]
    action = forms.ChoiceField(choices=choices)
    qty = forms.IntegerField(min_value=0, initial=0, required=False)
    desc = forms.CharField(widget=forms.TextInput(), required=False)

view.py:

product = Product.objects.get(id=p_id)
items = product.item_set.all()

forms = []

for item in items:
    tmp = ItemStockChangeForm()
    tmp.name = item.name
    tmp.stock = item.stock
    forms.append(tmp)


if request.method == 'POST':
    for form in forms:
        form = ItemStockChangeForm(request.POST)
        print (form.data['qty'])

context = {
    'forms':forms
}
return render(request, 'Warehouse/test.html', context)

test.html:

{% extends "Gudang/base.html" %}

{% block contentbody %}
    <form method="POST">
        <table class='table-stock'>
            {% csrf_token %}
            {% for form in forms %}
            {% if forloop.first %}
            <thead>
                <tr>
                    <th>
                        Name
                    </th>
                    <th>
                        Stock
                    </th>
                    {% for f in form %}
                    <th>
                        {{ f.label }}
                    </th>
                    {% endfor %}
                </tr>
            </thead>
            {% endif %}
            <tbody>
                <tr>
                    <td>
                        {{ form.name }}
                    </td>
                    <td>
                        {{ form.stock }}
                    </td>
                    {% for f in form %}
                    <td>
                        {{ f }}
                    </td>
                    {% endfor %}
                </tr>
            </tbody>
            {% endfor %}
        </table>
        <button type='submit'>Save</button>
    </form>
{% endblock contentbody %}

我以前尝试过使用formset,但是由于缺乏经验,我很难过。我也是2天前才开始使用django。

0 个答案:

没有答案