Saravanan Ragavan
Saravanan Ragavan

Reputation: 125

How to do simple arithmetic calculator in django template?

I want to show two sets of number from model in the django template for the same. I am using for loop to get each row data of the table to show in template as below :

{% for a in vis %}

{a.numone} {a.numtwo}

{% endfor %}

its working fine!.

Now, I want to do simple arithmetic calculation by using this numbers. say for example add, sub, div, multiply this two number and show it in template.

How to do it?

Question Updated below:

Model.py

class visits(models.Model):
doctor = models.ForeignKey(doctorprofile, on_delete=models.CASCADE)
patient = models.ForeignKey(patientprofile, on_delete=models.CASCADE)



visit_cons_fee = models.DecimalField(null=False, blank=False,  max_digits=10, decimal_places=2)
visit_other_fee = models.DecimalField(null=True, blank=True, max_digits=10, decimal_places=2)

def total_fee(self):
    return (self.visit_cons_fee + self.visit_other_fee)

def __str__ (self):
    return str(self.id)

views.py

vis=visits.objects.filter(patient=patid).values( 'visit_cons_fee','visit_other_fee', 'doctor__doc_Fname', 'doctor__doc_Lname' )

template as below:

{% for a in vis %}

Consultation Fees : {% if a.visit_cons_fee %}{{a.visit_cons_fee}}{% else %} 0 {% endif %}

Other Fees : {% if a.visit_other_fee %}{{a.visit_other_fee}}{% else %} 0 {% endif %}

Total Fees : ????

{% endfor %}

Upvotes: 0

Views: 516

Answers (1)

JanMalte
JanMalte

Reputation: 1060

Generic way

The template is not designed for any calculation or modification of data. It is used just for showing the data in the prefered way.

As all template need a view in django, just place the calculation in the view instead.

views.py

def your_view(request, *args, **kwargs):
    # ... your code
    vis = visits.objects.filter(patient=patid)
    for a in vis:
        a.calculated_value = make_calculation(a)
    context = {'vis': vis}
    return render(request, 'your_template.html', context)

your_template.html

{% for a in vis %}
  {{ a.numone }} {{ a.numtwo }} {{ a.calculated_value }}
{% endfor %}

Values are coming from the same model object

If the values for the calculation are coming from the same model instance, you could just add a method or property to your model and use this in your template.

models.py

class ModelA(models.Model):
    # ... your code
    @property
    def calculated_value(self):
        return (self.numone + self.numtwo * 2) / 25

your_template.html

{% for a in vis %}
  {{ a.numone }} {{ a.numtwo }} {{ a.calculated_value }}
{% en

Upvotes: 1

Related Questions