Django,从formset中提取值

j1dl9f46  于 2023-05-19  发布在  Go
关注(0)|答案(2)|浏览(241)

我已经覆盖了保存_formset方法来从管理页面提取数据。下面是我的代码的样子:

def save_formset(self, request, form, formset, change):
    for f in formset:
        print('Voter address is: ', f['voter_address'])
    super().save_formset(request,form, formset, change)

我得到的输出为:

但是我想提取实际的值,也就是“klncklas”,第二个,我想知道没有值存在。我如何才能做到这一点?

a11xaf1n

a11xaf1n1#

def save_formset(self, request, form, formset, change):
    # Create instances. Each instance will be a "row" (obj) of the inline model
    instances = formset.save(commit=False)
    # Iterate over the instances (objects of the Inline Model)
    for instance in instances:
        # Get the object's attribute (Model field)
        print(instance.voter_address)
    super().save_formset(request,form, formset, change)
xriantvc

xriantvc2#

在保存_formset()中,您需要使用formset.save(commit=False)来获取Django Admin中提交的内联对象,如下所示。* 不用担心formset.save(commit=False)不会保存对象,但会返回对象,而formset.save()相当于formset.save(commit=True)会保存和返回对象:

def save_formset(self, request, form, formset, change):
    for f in formset.save(commit=False): # Here
        print('Voter address is: ', f['voter_address'])
    super().save_formset(request, form, formset, change)

你可以在Django Admin中看到我的回答,解释了save(commit=False)save(),以及如何自定义提交的内联对象。

相关问题