These are two of few models in my project:
class Package(models.Model):
patient=models.ForeignKey(Patient, on_delete=CASCADE)
diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE)
treatment=models.ForeignKey(Treatment, on_delete=CASCADE)
patient_type=models.ForeignKey(PatientType, on_delete=CASCADE)
date_of_admission=models.DateField(default=None)
max_fractions=models.IntegerField(default=None)
total_package=models.DecimalField(max_digits=10, decimal_places=2)
package_date=models.DateTimeField(auto_now_add=True)
class Receivables(models.Model):
patient=models.ForeignKey(Patient, on_delete=CASCADE)
rt_number=models.CharField(max_length=15)
discount=models.DecimalField(max_digits=9, decimal_places=2, default=0)
approved_package=models.DecimalField(max_digits=10, decimal_places=2)
approval_date=models.DateField(default=None)
proposed_fractions=models.IntegerField()
done_fractions=models.IntegerField()
base_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True)
expected_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True)
receivables_date=models.DateTimeField(auto_now_add=True)
I needed the approved_package
in Receivables
to display a default
value calculated by subtracting discount
from the total_package
in Package
. And it should all be in real time. So I wrote an AJAX
code in Jquery
in an HTML
file and included
the file in my main template
. The code looks like:
<script>
$('select').change(function () {
var optionSelected = $(this).find("option:selected");
var valueSelected = optionSelected.val();
var textSelected = optionSelected.text();
var csr = $("input[name=csrfmiddlewaretoken]").val();
console.log(textSelected);
pkg={patient:textSelected, csrfmiddlewaretoken:csr}
$.ajax({
url:"{% url 'pt_name' %}",
method: "POST",
data: pkg,
dataType: "json",
success: function(data){
console.log(data);
console.log(data.pkg);
console.log(data.ptt);
var tp=data.pkg;
var ptt=data.ptt;
$('#id_discount').change(function(){
console.log('tp value: ', tp);
console.log('ptt value: ', ptt);
var discount=document.getElementById('id_discount').value;
console.log('discount value: ', discount);
var approved_package=document.getElementById('id_approved_package').value;
if (ptt=='CASH')
approved_package=tp-discount;
console.log('approved package new value: ', approved_package);
});
}
});
});
</script>
The code runs fine in the console
of the browser. It fires all the codes. It calculates the approved_package
but the result still does not show up in the field as a default value when I enter the discount
value. What is wrong with my code? Can someone point it out?