尝试将QuerySet作为初始数据传递给表单集 [英] Trying to pass a QuerySet as initial data to a formset

查看:82
本文介绍了尝试将QuerySet作为初始数据传递给表单集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为库存系统构建一个页面,使用户可以更新收到的物品数量。

I'm trying to build a page for an inventory system that will allow a user to update a quantity of items received.

我想显示所有产品的表格,并让用户输入收到的数量,然后将其过帐并进行迭代以更新数据库。

I want to show a table of all products and let the user enter the quantity received, which I'll post and iterate over to update the database.

这是我的观点:

def new_shipment(request):
    list_of_active_products = Product.objects.filter(status=1)
    ShipmentFormSet = formset_factory(ShipmentForm, extra=0)
    formset = ShipmentFormSet(initial=list_of_active_products)
    return render_to_response('inventory/new_shipment.html', {'formset': formset})

这是我的表单模型:

class ShipmentForm(forms.Form):
    sku = forms.IntegerField()
    product_name = forms.CharField(max_length=100)
    quantity = forms.IntegerField()

这是表单模板:

<form method="post" action="">
    <table>
        {% for form in formset %}
    {{ form }}
    {% endfor %}
    </table>    
    <input type="submit" />
</form>

这是我得到的错误:

呈现时捕获到AttributeError:产品对象没有属性获取

Caught AttributeError while rendering: 'Product' object has no attribute 'get'

有人可以帮我吗?

推荐答案

您还可以使用queryset参数。这应该起作用:

You can also use the queryset argument. This should work:


formset = ShipmentFormSet(queryset = list_of_active_products)

formset = ShipmentFormSet(queryset=list_of_active_products)

cf。 https://docs.djangoproject.com/en/ dev / topics / forms / modelforms /#changing-the-queryset

这篇关于尝试将QuerySet作为初始数据传递给表单集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆