django modelformset工厂'tuple'对象没有属性'author

时间:2019-01-17 19:55:48

标签: python django

如果数据发生更改,我正在尝试制作更新modelformset的表单,但是由于'tuple'对象在change_object中没有属性'author'而给出错误

def formformset_update(request,invoice_id):
    # Sale_Transiction_formset = modelformset_factory(SaleTransiction, form=Sale_Invoice_Main_Page_ModelForm,extra=1)
    if request.method == 'POST':
        forms = Sale_Invoice_Main_Page_ModelForm(request.POST,instance=SaleInvoice.objects.get(invoice_no=invoice_id))
        formset = Sale_Transction_formset_Extra(request.POST, request.FILES,queryset=SaleTransiction.objects.filter(invoice_no=invoice_id))

        if formset.is_valid() and forms.is_valid():
            forms.save()
            transiction = formset.save(commit=False)
            inv_no = forms.cleaned_data['invoice_no']
            customer = forms.cleaned_data['customer']
            trans_date = forms.cleaned_data['invoice_date']
            forms.author = request.user

            # for ins in transiction:
            #     ins.invoice_no = inv_no
            #     ins.customer_transiction_name = 'class'
            #     ins.transiction_date = trans_date
            #     ins.transiction_type = 'sale'
            #     ins.author = str(request.user)
            #     ins.save()

            for obj in formset.deleted_objects:
                obj.delete()

            for objs in formset.changed_objects:

                # objs.author = request.user
                objs.customer_transiction_name = customer
                objs.transiction_date = trans_date
                objs.save()

            for ins in formset.new_objects:
                ins.invoice_no = inv_no
                ins.customer_transiction_name = customer
                ins.transiction_date = trans_date
                ins.transiction_type = 'sale'
                ins.author = request.user
                ins.save()

            return HttpResponseRedirect(reverse_lazy('saleinvoice:sale invoice home page'))
    else:
        # sale_invoice = Invoice_max.objects.get(invoice_name='sale')
        forms = Sale_Invoice_Main_Page_ModelForm(instance=SaleInvoice.objects.get(invoice_no=invoice_id))
        formset = Sale_Transction_formset_Extra(queryset=SaleTransiction.objects.filter(invoice_no=invoice_id))
    return render(request, 'saleinvoice/sale test/sale formformmodel update.html' ,{ "saleform" : forms,
                                                                       "saletransiction" : formset })

model



 class SaleInvoice(models.Model):
    customer = models.ForeignKey(Customer_data , on_delete=models.CASCADE)
    invoice_date = models.DateField(null=True,blank=True)
    invoice_no = models.PositiveIntegerField(unique=True)
    due_date = models.DateField(blank=True,null=True)
    address = models.TextField()
    total_amount = models.PositiveIntegerField(null=True,blank=True)
    description = models.TextField(null=True,blank=True)
    transiction_type = models.CharField(max_length=50,blank=True)
    author = models.CharField(max_length=30,null=True,blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return str(self.invoice_no)


class SaleTransiction(models.Model):
    invoice_no = models.PositiveIntegerField()
    customer_transiction_name = models.CharField(max_length=30)
    transiction_date = models.DateField()
    item = models.CharField(max_length=100)
    description = models.TextField(null=True,blank=True)
    price = models.PositiveIntegerField()
    quantity = models.PositiveIntegerField()
    total = models.PositiveIntegerField()
    transiction_type = models.CharField(max_length=50)
    author = models.CharField(max_length=30)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.item

表格

class Sale_Invoice_Main_Page_ModelForm(forms.ModelForm):

    class Meta:
        model = SaleInvoice
        fields = '__all__'
        exclude = ['created_at','updated_at']
        widgets = {'description' : forms.TextInput(attrs={'placeholder': 'Description'}),
                   'address' : forms.Textarea(attrs={ 'readonly' : True, 'placeholder' : 'Address'}),
                   'invoice_date' : forms.DateInput(attrs={ 'class' : "vdate", 'placeholder' : "Date" }),
                   'total_amount' : forms.NumberInput(attrs={ 'readonly' : True }),
                   'due_date' : forms.DateInput(attrs={ 'readonly' : "True" }),
                   'invoice_no' : forms.NumberInput(attrs={'readonly' : True})
                   }

Sale_Transction_formset_Extra = modelformset_factory(SaleTransiction,
                                               fields= ['item','price','description','quantity','total'],
                                               extra=1,

                                               widgets={ 'description' : forms.TextInput(attrs={ 'placeholder' : 'optionall','class' : 'description'}),
                                                         'price' : forms.NumberInput(attrs={ 'readonly' : 'True', 'class' : 'rate'}),
                                                         'total' : forms.NumberInput(attrs={ 'readonly' : 'True', 'class' : 'total'}),
                                                         'quantity' : forms.NumberInput(attrs={'class' : 'quantity'}),
                                                         'item' : forms.TextInput(attrs={ 'class' : "item_list",'readonly' : True})
                                                         # 'item' : forms.Select(choices=Product.objects.all().values_list('id','product_name'),attrs={ 'class' : "item_list"}),
                                                          },
                                               can_delete=True
                                               )

当我更改数据并保存数据然后在formset.changed_objects中输入objs时:循环是“元组”对象没有属性“ customer_transiction_name”的错误,这是gen错误

1 个答案:

答案 0 :(得分:0)

那是因为“ changed_objects”不会像使用“ deleted_objects”或“ new_objects”获得的那样返回简单的对象列表。它返回一个元组列表,其中每个元组都由对象组成,后跟一个其值已更改的字段列表:

[(对象,['changed_field1','changed_field2'])]

因此,您需要通过指向元组中的第一项来调整代码:

for objs in formset.changed_objects:
    objs[0].customer_transiction_name = customer
    objs[0].transiction_date = trans_date
    objs[0].save()