Calculation of input value and store it into database django

I want per unit price value according to input value and save it on database, I don’t know how to do this task kindly help me plz

class Celldetail(models.Model):
    CellInvoiceNo = models.IntegerField(null=True, blank=True)
    Cell_Type = models.CharField(max_length=200, null=True)
    Cell_qty = models.DecimalField(default=0)
    Cell_price = models.DecimalField(default=0)
    Cell_PUP = models.FloatField()

def add_inventory_view(request):
    form = CellForm(request.POST or None)
    if form.is_valid():
    context = {
        'form': form,
    return render(request, "addinventory.html", context)

>Solution :

Override the save() function of your model:

class CellDetail(models.Model): # note Pascal case

   def save(self, *args, **kwargs):
      self.Cell_PUP = self.Cell_price / self.Cell_qty
      super(CellDetail, self).save(*args, **kwargs)

I would recommend renaming your fields to be clearer, remove the unnecessary prefix, and to use snake case, e.g.

invoice_no = ...
type = ...
quantity = ...
price = ...
per_unit_price = ...

Leave a Reply