A Django app to make simple calculations in your django forms
Project description
django-calculation
Make simple calculations in your django forms using django-calculation
. This app provide a Django Widget that derives its value from a expression defined in the widget instance.
The field is updated when any of the source fields change.
Installation
pip install django-calculation
Add calculation
to your INSTALLED_APPS
INSTALLED_APPS = [
...
'calculation',
]
Usage
Import calculation
and complete the definition.
Example
Using FormulaInput
widget
from django import forms
import calculation
class TestForm(forms.Form):
quantity = forms.DecimalField()
price = forms.DecimalField()
amount = forms.DecimalField(
widget=calculation.FormulaInput('quantity*price') # <- using single math expression
)
tax = forms.DecimalField(
widget=calculation.FormulaInput('parseFloat(amount/11).toFixed(2)') # <-- using math expression and javascript functions.
)
Modes
Currently the app support two modes of calculation FORMULA
and SUMMARY
.
FORMULA
The field value derive from a formula expression. In the expression you can refer to the form field using its name.
amount = forms.DecimalField(
widget=calculation.FormulaInput('quantity*price')
)
SUMMARY
The field value derive from a summary definition, it is useful when you need to get the sum of a django formset field.
total = forms.DecimalField(
widget=calculation.SummaryInput(
function=calculation.SUM,
field='amount'
)
Summary example
Summary definition in OrderForm
class OrderForm(forms.ModelForm):
total = forms.DecimalField(
# using SumInput a SummaryInput abstraction
widget=calculation.SumInput('subtotal')
)
class Meta:
model = Order
fields = ['date', 'customer']
OrderDetForm
also contain a calculated field subtotal
.
class OrderDetForm(forms.ModelForm):
subtotal = forms.DecimalField(
widget=calculation.FormulaInput('quantity*price')
)
class Meta:
model = OrderDet
fields = ['product', 'price', 'quantity', 'subtotal']
# formset definition
OrderDetFormSet = forms.inlineformset_factory(Order, OrderDet, OrderDetForm)
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for django_calculation-0.0.9-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | cba93f829dd6308c1816cc963ba21eca2ceeec055b5366c71628374bb09a8196 |
|
MD5 | 363b4057a2478982a76b7adf5848c46a |
|
BLAKE2b-256 | 79cb1d57372b59d6f3f1698f7cdae66628a1afce775d8f0aa35a2db93481f243 |