[Answer]-Django forms and javascript or maybe some other way to do the same

1👍

✅

If you want to show the values to the user as he is filling in the form, you’ll need JavaScript. At least I don’t know any other client side technique to do this. Your real big problem here is to persist the data to database. You can’t rely to the client that the proper values are going to be saved in the database. For this purpose you could overwrite the save method of the model. This is a simple example:

def save(self, *args, **kwargs):
    self.iva = self.importe_sin_iva * 0.21
    self.importe_Total = self.iva + self.importe_sin_iva
    super(Factura, self).save(*args, **kwargs)

In the form you can use the event ‘onchange’ to update the appropriate fields on the fly. The framework jQuery is ideal for this.
Your function could look like this:

$('#importe_sin_iva').change(function() {
    var importe_sin_iva = $(#importe_sin_iva).val()
    var iva = importe_sin_iva * 0.21
    $('#iva').val(iva)
    var total = importe_sin_iva + iva
    $('#total').val(total)
});

This is also a simple example, where the input fields for importe_sin_iva, iva and importe_Total have the IDs importe_sin_iva, iva and total respectively. The fields iva and total shouldn’t be persisted to the database. You can’t rely on client side techniques for validation of the values.

You still have to learn how to use jQuery, how to bind it to your HTML, etc. I hope these simple examples can point you the way.

Leave a comment