Helper Functions
Some common functions are provided for use in custom report and label templates. To include these, load the report
functions at the start of the template:
<!-- Load the report helper functions -->
{% load report %}
Use the Source, Luke
To see the full range of available helper functions, refer to the source file report.py where these functions are defined!
Assigning Variables¶
When making use of helper functions within a template, it can be useful to store the result of the function to a variable, rather than immediately rendering the output.
For example, using the render_currency helper function, we can store the output to a variable which can be used at a later point in the template:
{% load report %}
{% render_currency 12.3 currency='USD' as myvar %}
...
...
Result: {{ myvar }}
Data Structure Access¶
A number of helper functions are available for accessing data contained in a particular structure format:
Index Access¶
To return the element at a given index in a container which supports indexed access (such as a list), use the getindex
function:
Parameters:
Name | Type | Description | Default |
---|---|---|---|
container |
list
|
A python list object |
required |
index |
int
|
The index to retrieve from the list |
required |
Example¶
{% getindex my_list 1 as value %}
Item: {{ value }}
Key Access¶
To return an element corresponding to a certain key in a container which supports key access (such as a dictionary), use the getkey
function:
Parameters:
Name | Type | Description | Default |
---|---|---|---|
container |
dict
|
A python dict object |
required |
key |
str
|
The 'key' to be found within the dict |
required |
Example¶
<ul>
{% for key in keys %}
{% getkey my_container key as value %}
<li>{{ key }} = {{ value }}</li>
{% endfor %}
</ul>
Database Helpers¶
A number of helper functions are available for accessing database objects:
filter_queryset¶
The filter_queryset
function allows for arbitrary filtering of the provided querysert. It takes a queryset and a list of filter arguments, and returns a filtered queryset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
queryset |
QuerySet
|
The queryset to filter |
required |
Other Parameters:
Name | Type | Description |
---|---|---|
field |
any
|
Filter the queryset based on the provided field |
Provided QuerySet
The provided queryset must be a valid Django queryset object, which is already available in the template context.
Advanced Users
The filter_queryset
function is a powerful tool, but it is also easy to misuse. It assumes that the user has a good understanding of Django querysets and the underlying database structure.
Example¶
In a report template which has a PurchaseOrder
object available in its context, fetch any line items which have a received quantity greater than zero:
{% load report %}
{% filter_queryset order.lines.all received__gt=0 as received_lines %}
<ul>
{% for line in received_lines %}
<li>{{ line.part.part.full_name }} - {{ line.received }} / {{ line.quantity }}</li>
{% endfor %}
</ul>
filter_db_model¶
The filter_db_model
function allows for filtering of a database model based on a set of filter arguments. It takes a model class and a list of filter arguments, and returns a filtered queryset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_name |
str
|
The name of the Django model - including app name (e.g. 'part.partcategory') |
required |
Other Parameters:
Name | Type | Description |
---|---|---|
field |
any
|
Filter the queryset based on the provided field |
Example¶
Generate a list of all active customers:
{% load report %}
{% filter_db_model company.company is_customer=True active=True as active_customers %}
<ul>
{% for customer in active_customers %}
<li>{{ customer.name }}</li>
{% endfor %}
</ul>
Advanced Database Queries¶
More advanced database filtering should be achieved using a report plugin, and adding custom context data to the report template.
Number Formatting¶
format_number¶
The helper function format_number
allows for some common number formatting options. It takes a number (or a number-like string) as an input, as well as some formatting arguments. It returns a string containing the formatted number:
Parameters:
Name | Type | Description | Default |
---|---|---|---|
decimal_places |
Optional[int]
|
Number of decimal places to render |
None
|
integer |
bool
|
Boolean, whether to render the number as an integer |
False
|
leading |
int
|
Number of leading zeros (default = 0) |
0
|
separator |
Optional[str]
|
Character to use as a thousands separator (default = None) |
None
|
Example¶
{% load report %}
{% format_number 3.14159265359 decimal_places=5, leading=3 %}
<!-- output: 0003.14159 -->
{% format_number 3.14159265359 integer=True %}
<!-- output: 3 -->
Date Formatting¶
For rendering date and datetime information, the following helper functions are available:
format_date¶
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dt |
date
|
The date to format |
required |
timezone |
Optional[str]
|
The timezone to use for the date (defaults to the server timezone) |
None
|
fmt |
Optional[str]
|
The format string to use (defaults to ISO formatting) |
None
|
format_datetime¶
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dt |
datetime
|
The datetime object to format |
required |
timezone |
Optional[str]
|
The timezone to use for the date (defaults to the server timezone) |
None
|
fmt |
Optional[str]
|
The format string to use (defaults to ISO formatting) |
None
|
Date Formatting¶
If not specified, these methods return a result which uses ISO formatting. Refer to the datetime format codes for more information! |
Example¶
A simple example of using the date formatting helper functions:
{% load report %}
Date: {% format_date my_date timezone="Australia/Sydney" %}
Datetime: {% format_datetime my_datetime format="%d-%m-%Y %H:%M%S" %}
Currency Formatting¶
render_currency¶
The helper function render_currency
allows for simple rendering of currency data. This function can also convert the specified amount of currency into a different target currency:
Parameters:
Name | Type | Description | Default |
---|---|---|---|
money |
Money
|
The Money instance to be rendered |
required |
decimal_places |
Optional[int]
|
The number of decimal places to render to. If unspecified, uses the PRICING_DECIMAL_PLACES setting. |
None
|
currency |
Optional[str]
|
Optionally convert to the specified currency |
None
|
min_decimal_places |
Optional[int]
|
The minimum number of decimal places to render to. If unspecified, uses the PRICING_DECIMAL_PLACES_MIN setting. |
None
|
max_decimal_places |
Optional[int]
|
The maximum number of decimal places to render to. If unspecified, uses the PRICING_DECIMAL_PLACES setting. |
None
|
include_symbol |
bool
|
If True, include the currency symbol in the output |
True
|
Example¶
{% load report %}
<em>Line Item Unit Pricing:</em>
<ul>
{% for line in order.lines %}
<li>{% render_currency line.price currency=order.supplier.currency %}</li>
{% endfor %}
</ul>
Total Price: {% render_currency order.total_price currency='NZD' decimal_places=2 %}
Maths Operations¶
Simple mathematical operators are available, as demonstrated in the example template below:
add¶
subtract¶
multiply¶
divide¶
Example¶
<!-- Load the report helper functions -->
{% load report %}
{% add 1 3 %} <!-- Add two numbers together -->
{% subtract 4 3 %} <!-- Subtract 3 from 4 -->
{% multiply 1.2 3.4 %} <!-- Multiply two numbers -->
{% divide 10 2 as division_result %} <!-- Divide 10 by 2 -->
Division Result: {{ division_result }}
These operators can also be used with variables:
{% load report %}
{% for line in order.lines %}
Total: {% multiply line.purchase_price line.quantity %}<br>
{% endfor %}
Media Files¶
Media files are any files uploaded to the InvenTree server by the user. These are stored under the /media/
directory and can be accessed for use in custom reports or labels.
uploaded_image¶
You can access an uploaded image file if you know the path of the image, relative to the top-level /media/
directory. To load the image into a report, use the {% uploaded_image ... %}
tag:
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filename |
str
|
The filename of the image relative to the MEDIA_ROOT directory |
required |
replace_missing |
bool
|
Optionally return a placeholder image if the provided filename does not exist (default = True) |
True
|
replacement_file |
str
|
The filename of the placeholder image (default = 'blank_image.png') |
'blank_image.png'
|
validate |
bool
|
Optionally validate that the file is a valid image file |
True
|
width |
Optional[int]
|
Optional width of the image |
None
|
height |
Optional[int]
|
Optional height of the image |
None
|
rotate |
Optional[float]
|
Optional rotation to apply to the image |
None
|
Returns:
Type | Description |
---|---|
str
|
Binary image data to be rendered directly in a tag |
Raises:
Type | Description |
---|---|
FileNotFoundError
|
If the file does not exist |
<!-- Load the report helper functions -->
{% load report %}
<img src='{% uploaded_image "subdir/my_image.png" width=480 rotate=45 %}'/>
Missing Image
If the supplied image filename does not exist, it will be replaced with a placeholder image file
Invalid Image
If the supplied file is not a valid image, it will be replaced with a placeholder image file
Image Manipulation¶
The {% uploaded_image %}
tag supports some optional parameters for image manipulation. These can be used to adjust or resize the image - to reduce the size of the generated report file, for example.
{% load report %}
<img src='{% uploaded_image "image_file.png" width=500 rotate=45 %}'>
encode_svg_image¶
SVG images need to be handled in a slightly different manner. When embedding an uploaded SVG image, use the {% encode_svg_image ... %}
tag:
<!-- Load the report helper functions -->
{% load report %}
<img src='{% encode_svg_image svg_image_file %}'/>
part_image¶
A shortcut function is provided for rendering an image associated with a Part instance. You can render the image of the part using the {% part_image ... %}
template tag:
Parameters:
Name | Type | Description | Default |
---|---|---|---|
part |
Part
|
A Part model instance |
required |
preview |
bool
|
Return the preview image (default = False) |
False
|
thumbnail |
bool
|
Return the thumbnail image (default = False) |
False
|
Raises:
Type | Description |
---|---|
TypeError
|
If provided part is not a Part instance |
<!-- Load the report helper functions -->
{% load report %}
<img src='{% part_image part %}'/>
Image Arguments¶
Any optional arguments which can be used in the uploaded_image tag can be used here too.
Image Variations¶
The Part model supports preview (256 x 256) and thumbnail (128 x 128) versions of the uploaded image. These variations can be used in the generated reports (e.g. to reduce generated file size):
{% load report %}
<!-- Render the "preview" image variation -->
<img src='{% part_image part preview=True %}'>
<!-- Render the "thumbnail" image variation -->
<img src='{% part_image part thumbnail=True %}'>
company_image¶
A shortcut function is provided for rendering an image associated with a Company instance. You can render the image of the company using the {% company_image ... %}
template tag:
Parameters:
Name | Type | Description | Default |
---|---|---|---|
company |
Company
|
A Company model instance |
required |
preview |
bool
|
Return the preview image (default = False) |
False
|
thumbnail |
bool
|
Return the thumbnail image (default = False) |
False
|
Raises:
Type | Description |
---|---|
TypeError
|
If provided company is not a Company instance |
<!-- Load the report helper functions -->
{% load report %}
<img src='{% company_image company %}'/>
Image Variations¶
Preview and thumbnail image variations can be rendered for the company_image
tag, in a similar manner to part image variations
Icons¶
Some models (e.g. part categories and locations) allow to specify a custom icon. To render these icons in a report, there is a {% icon location.icon %}
template tag from the report template library available.
This tag renders the required html for the icon.
Loading fonts
Additionally the icon fonts need to be loaded into the template. This can be done using the {% include_icon_fonts %}
template tag inside of a style block
Custom classes for styling the icon further
The icon template tag accepts an optional class
argument which can be used to apply a custom class to the rendered icon used to style the icon further e.g. positioning it, changing it's size, ... {% icon location.icon class="my-class" %}
.
{% load report %}
{% block style %}
{% include_icon_fonts %}
{% endblock style %}
{% icon location.icon %}
InvenTree Logo¶
A template tag is provided to load the InvenTree logo image into a report. You can render the logo using the {% logo_image %}
tag:
{% load report %}
<img src='{% logo_image %}'/>
Custom Logo¶
If the system administrator has enabled a custom logo then this logo will be used instead of the base InvenTree logo.
This is a useful way to get a custom company logo into your reports.
If you have a custom logo, but explicitly wish to load the InvenTree logo itself, add custom=False
to the tag:
{% load report %}
<img src='{% logo_image custom=False %}'/>
Report Assets¶
Report Assets are files specifically uploaded by the user for inclusion in generated reports and labels.
You can add asset images to the reports and labels by using the {% asset ... %}
template tag:
<!-- Load the report helper functions -->
{% load report %}
<img src="{% asset 'my_awesome_logo.png' %}"/>
Part Parameters¶
If you need to load a part parameter for a particular Part, within the context of your template, you can use the part_parameter
template tag:
Parameters:
Name | Type | Description | Default |
---|---|---|---|
part |
Part
|
A Part object |
required |
parameter_name |
str
|
The name of the parameter to retrieve |
required |
Returns:
Type | Description |
---|---|
str
|
A PartParameter object, or None if not found |
Example¶
The following example assumes that you have a report or label which contains a valid Part instance:
{% load report %}
{% part_parameter part "length" as length %}
Part: {{ part.name }}<br>
Length: {{ length.data }} [{{ length.units }}]
A Part Parameter has the following available attributes:
Attribute | Description |
---|---|
Name | The name of the parameter (e.g. "Length") |
Description | The description of the parameter |
Data | The value of the parameter (e.g. "123.4") |
Units | The units of the parameter (e.g. "km") |
Template | A reference to a PartParameterTemplate |