无法保存django模板中的项目列表

时间:2016-04-26 15:59:40

标签: python django django-models django-forms django-templates

产品有很多项目。我可以整齐地在表格中显示特定产品的项目。但是当我尝试保存时,在回发时只会保存表中的最后一个元素以用于该产品的所有项目。这可能是因为我只从我的html返回最后一个元素。任何人都可以告诉我任何优雅的方式来做到这一点?这是我的代码。

models.py

class Item(models.Model):
    Product = models.ForeignKey("Product", related_name = "Attributes")
    Name = models.CharField(max_length=1000, blank=True, null=True)
    Type = models.CharField(max_length=1000, blank=True, null=True)

forms.py

class ItemForm(ModelForm):
    class Meta:
        model = Item
        fields = ['Name', 'Tag']

views.py

def getItems(request, product_id):
    items = get_list_or_404(Item, Product = product_id)
    itemslist = []
    if request.method == 'GET':
        for item in items:
            itemform = ItemForm(instance=item)
            itemlist.append(itemform)
    else:
        for item in items:
            itemform = ItemForm(request.POST, instance=item)
            itemlist.append(itemform)
        for tempform in itemlist:
            if tempform.is_valid():
                tempform.save()
    return render(request, 'knowledgebase.html', {'product_id': product_id, 'itemslist': itemslist})

html文件:

<tbody>
    {% for itemform in itemslist%}
        <tr>
            <td class="td"> {{ itemform.Name }} </td>
            <td> {{ itemform.Tag }} </td>
        </tr>
    {% endfor %}
</tbody>

1 个答案:

答案 0 :(得分:1)

唯一的最后一种形式是保存,因为您要向模板发送要呈现的各个表单的列表。如果没有看到你的其他HTML,我说你只有一个提交按钮。由于其他表单没有在提交时提供数据,因此它们不被视为绑定,因此在调用is_valid()时将不会返回True并且不会到达tempform.save() https://docs.djangoproject.com/en/1.9/ref/forms/api/#bound-and-unbound-forms

尝试打印出每个tempform.is_bound()的值来测试它。

缓解这种情况的一种方法是使用formset或为每个模型实例创建自己的自定义表单,其中包含多个字段。

相关问题