Django inlineformset - custom save method
This is my models.py
class Invoices(models.Model):
...
sum_w_vat = models.DecimalField(max_digits=7, decimal_places=2, default=0)
sum_wo_vat = models.DecimalField(max_digits=7, decimal_places=2, default=0)
sum_discount = models.DecimalField(max_digits=7, decimal_places=2, default=0)
sum_vat = models.DecimalField(max_digits=7, decimal_places=2, default=0)
sum_paid = models.DecimalField(max_digits=7, decimal_places=2, default=0)
...
class InvoiceItems(models.Model):
invoice = models.ForeignKey(Invoices)
quantity = models.DecimalField(max_digits=9, decimal_places=2)
unit = models.ForeignKey(StocklistUnits, verbose_name='Merska enota')
price = models.DecimalField(max_digits=9, decimal_places=2)
vat = models.DecimalField(max_digits=4, decimal_places=3)
discount = models.DecimalField(max_digits=3, decimal_places=1)
def save(self, **kwargs):
self.invoice.sum_w_vat += (self.price * self.quantity * self.vat) * self.discount
self.invoice.sum_wo_vat += (self.price * self.quantity) * self.discount
self.invoice.sum_discount += (self.price * self.quantity) * ( self.discount / 100 )
self.invoice.sum_vat += ((self.price * self.quantity * self.vat) * self.discount) - ((self.price * self.quantity) * self.discount)
super(InvoicesItems, self).save(**kwargs)
I don't know how to save the calculated data in the InvoiceItems
redefined save function... this obviously doesn't work, because Invoices
get saved first...
views.py
def edit(request, id = None):
InvoiceFormSet = inlineformset_factory(Invoices, InvoicesItems)
if id == None:
initial_data = ''
data = Invoices()
else:
data = get_object_or_404(Invoices, pk=id)
initial_data = ''
if request.method == 'POST':
created_invoice = InvoicesForm(request.POST, instance=data)
form = InvoiceFormSet(request.POST, instance=data)
if not form.is_valid() and not created_invoice.is_valid():
//json err msg
else:
created_invoice.save()
form.save()
json = simplejson.dumps(response, ensure_ascii=False)
return HttpResponse(json, mimetype="application/json")
else:
form = InvoicesForm(instance=data, initial=initial_data)
form_items = InvoiceFormSet(instance=data)
c = {'form':form, 'form_items':form_items}
c.update(csrf(request))
return render_to_response('crud_invoice_开发者_开发知识库edit.html', c)
How can I iterate through the InvoiceItems
and calculate the field which then need to be inserted into Invoices
. I'm new to django...
Thank you!
I don't know if this is the right way... but it works...
All I had to do was to save the created_invoice
again... so
created_invoice.save()
form.save()
created_invoice.save()
精彩评论