Reputation: 19
I have form
amount = forms.IntegerField(label='Amount :',help_text='enter price')
and templates html
{% if contact_data.amount %}
<h4> Amount : {{ contact_data.amount }}</h4>
I would like to print in templates html 'amount' and 'amount' *1,75 and 'amount' /0.45 ? How is best solution
Upvotes: 0
Views: 144
Reputation: 2167
If you want to do this in views and you are using Class-Based Views, use the ContextMixin to add the pre-calculated values to your context that gets passed to the template.
In views.py
:
from django.views.generic import DetailView
from .models import YourModel
class YourModelDetailView(DetailView):
model = YourModel
def get_context_data(self, **kwargs):
context = super(YourModelDetailView, self).get_context_data(**kwargs)
context['amount_mult'] = self.contact_data.amount * 1.75
context['amount_div'] = self.contact_data.amount / 0.45
return context
Then in your template, you use something like: {{ amount_mult }}
and {{ amount_div }}
.
Upvotes: 0
Reputation: 376
I'm not sure that I understand the question...but if what you want to do is display amount
, amount * 1.75
and mount / 0.45
(not sure if you meant to multiply again here). Then....there are a number of ways to do this.
Some will argue that you should probably calculate all these values in the view and then just surface them in the template. An example on how to pass data from a view to the template is here:
from django.shortcuts import render_to_response
def my_view(request):
# Assuming a function get_contact_data() because I don't know where you are
# getting this.
contact_data = get_contact_data()
return render_to_response(
'polls/detail.html',
{
'amount_one': contact_data.amount,
'amount_two': contact_data.amount * 1.75,
'amount_three': contact_data.amount / 0.45,
}
)
# And then in the template...
<h4> Amount One: {{ amount_one }}</h4>
<h4> Amount Two: {{ amount_two }}</h4>
<h4> Amount Three: {{ amount_three }}</h4>
The easy way out would be to handle this in the template. In which case, I would recommend using django-mathfilters. This would allow you to do the following in the template:
<h4> Amount : {{ contact_data.amount }}</h4>
<h4> Amount : {{ contact_data.amount|mul:1.75 }}</h4>
<h4> Amount : {{ contact_data.amount|div:0.45 }}</h4>
If contact_data is a Data Model of some sort, you could handle it at the model level:
from django.db import models
class ContactData(models.Model):
amount = models.IntegerField()
@property
def amount_two(self):
return self.amount * 1.75
@property
def amount_three(self):
return self.amount / 0.45
# And then in the template...
<h4> Amount One: {{ contact_data.amount }}</h4>
<h4> Amount Two: {{ contact_data.amount_two }}</h4>
<h4> Amount Three: {{ contact_data.amount_three }}</h4>
Upvotes: 2