'Save method is not being called in StackedInline model admin in Django

models.py

class form21tablet(models.Model):
   date = models.DateField()
   TotalNetWt = models.DecimalField(max_digits=8, decimal_places=3,default=0,  editable=False, null=True, blank=True)
   yieldPercent = models.DecimalField(max_digits=4, decimal_places=2, default=0, editable=False, null=True, blank=True)
    
    def save(self):
        #self.save()
    
        print('hello This is Before if')
    
        #calculation of total and percentage
        totnet=0
        totgross= 0
        # print('Hi', self.form21entry_set.all())
        for item in self.form21entry_set.all():
            print('Hi')
            totnet += item.net
            totgross += item.gros
        print(totnet)
        print(totgross)
        self.TotalNetWt = totnet
        if totgross:
            self.yieldPercent = totnet*100/totgross
        print(self.TotalNetWt)
        print(self.yieldPercent)
        super().save()


class form21entry(models.Model):
   formref = models.ForeignKey(form21tablet, on_delete=models.CASCADE) 
   Date = models.DateField()`
   ContainerNo = models.IntegerField()
   tare = models.DecimalField(max_digits=5, decimal_places=3, verbose_name='Tare Wt.(KG)')
   gros = models.DecimalField(max_digits=5, decimal_places=3, verbose_name='Gross Wt.(KG)')
   net = models.DecimalField(max_digits=5, decimal_places=3, verbose_name='Net Wt.(KG)', editable=False)
   done_by = models.CharField(max_length=50)
   Checked_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+')
   answer = (`
`('1', 'Ok'),`
`('0', 'Not Ok')`
`)
   Remarks = models.CharField(max_length=50, choices=answer)

    def save(self):
        self.net = self.gros - self.tare
        return super().save()
    def __str__(self):
        return str(self.Date) + ' - ' + str(self.ContainerNo)

admin.py

class form21entryInline(admin.StackedInline):
   model = form21entry


class form21tabletAdmin(admin.ModelAdmin):
   list_display = ['date', 'TotalNetWt', 'yieldPercent']
   inlines = [form21entryInline]`
   readonly_fields = ('TotalNetWt', 'yieldPercent')

   class Meta:
      model = form21tablet

admin.site.register(form21tablet, form21tabletAdmin)

I am trying to get the calculations when I save the form but I am not getting any answers when I save it once, if I save it twice it returns me all the calculations.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source