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 }}
Note the use of the as keyword to assign the output of the function to a variable. This can be used to assign the result of a function to a named variable, which can then be used later in the template.
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 |
backup_value
|
Optional[Any]
|
A backup value to return if the key is not found |
None
|
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:
order_queryset¶
The order_queryset function allows for ordering of a provided queryset. It takes a queryset and a list of ordering arguments, and returns an ordered queryset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
queryset
|
QuerySet
|
The queryset to order |
required |
Other Parameters:
| Name | Type | Description |
|---|---|---|
field |
str
|
Order 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.
Example¶
In a report template which has a PurchaseOrder object available in its context as the variable order, return the matching line items ordered by part name:
{% load report %}
{% order_queryset order.lines.all 'part__name' as ordered_lines %}
filter_queryset¶
The filter_queryset function allows for arbitrary filtering of the provided queryset. 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:
{% raw %}
{% 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 |
|---|---|---|---|
number
|
int | float | Decimal
|
The number to be formatted |
required |
decimal_places
|
Optional[int]
|
Number of decimal places to render |
None
|
multiplier
|
Optional[int | float | Decimal]
|
Optional multiplier to apply to the number before formatting |
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
|
multiplier
|
Optional[Decimal]
|
An optional multiplier to apply to the money amount before rendering |
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 %}
convert_currency¶
To convert a currency value from one currency to another, use the convert_currency helper function:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
money
|
Money
|
The Money instance to be converted |
required |
currency
|
Optional[str]
|
The target currency code (e.g. 'USD', 'EUR', etc.) |
None
|
Data Types
The money parameter must be Money class instance. If not, an error will be raised.
create_currency¶
Create a currency instance using the create_currency helper function. This returns a Money class instance based on the provided amount and currency type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amount
|
str | int | float | Decimal
|
The numeric amount (a numeric type or string) |
required |
currency
|
Optional[str]
|
The currency code (e.g. 'USD', 'EUR', etc.) |
None
|
Maths Operations¶
Simple mathematical operators are available, as demonstrated in the example template below. These operators can be used to perform basic arithmetic operations within the report template.
Input Types
These mathematical functions accept inputs of various input types, and attempt to perform the operation accordingly. Note that any inputs which are provided as strings or numbers will be converted to Decimal class types before the operation is performed.
add¶
Add two numbers together using the add helper function:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
The first value to add |
required |
y
|
Any
|
The second value to add |
required |
cast
|
Optional[type]
|
Optional type to cast the result to (e.g. int, float, str) |
None
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
If the values cannot be added together |
subtract¶
Subtract one number from another using the subtract helper function:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
The value to be subtracted from |
required |
y
|
Any
|
The value to be subtracted |
required |
cast
|
Optional[type]
|
Optional type to cast the result to (e.g. int, float, str) |
None
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
If the values cannot be subtracted |
multiply¶
Multiply two numbers together using the multiply helper function:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
The first value to multiply |
required |
y
|
Any
|
The second value to multiply |
required |
cast
|
Optional[type]
|
Optional type to cast the result to (e.g. int, float, str) |
None
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
If the values cannot be multiplied together |
divide¶
Divide one number by another using the divide helper function:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
The value to be divided |
required |
y
|
Any
|
The value to divide by |
required |
cast
|
Optional[type]
|
Optional type to cast the result to (e.g. int, float, str) |
None
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
If the values cannot be divided |
modulo¶
Perform a modulo operation using the modulo helper function:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
The first value to be used in the modulo operation |
required |
y
|
Any
|
The second value to be used in the modulo operation |
required |
cast
|
Optional[type]
|
Optional type to cast the result to (e.g. int, float, str) |
None
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
If the values cannot be used in a modulo operation |
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 -->
<!-- Perform a calculation and store the result -->
{% 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 |
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' %}"/>
Parameters¶
If you need to load a parameter value for a particular model instance, within the context of your template, you can use the parameter template tag:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance
|
Model
|
A Model object |
required |
parameter_name
|
str
|
The name of the parameter to retrieve |
required |
Returns:
| Type | Description |
|---|---|
Optional[Parameter]
|
A Parameter 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 %}
{% parameter part "length" as length %}
Part: {{ part.name }}<br>
Length: {{ length.data }} [{{ length.units }}]
A 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 ParameterTemplate |
Rendering Markdown¶
Some data fields (such as the Notes field available on many internal database models) support markdown formatting. To render markdown content in a custom report, there are template filters made available through the django-markdownify library. This library provides functionality for converting markdown content to HTML representation, allowing it to be then rendered to PDF by the InvenTree report generation pipeline.
To render markdown content in a report, consider the following simplified example:
{% load markdownify %}
<h3>Part Notes</h3>
<p>
{{ part.notes | markdownify }}
</p>
You can read further details in the django-markdownify documentation.
List of tags and filters¶
The following tags and filters are available.
Tags¶
| Namespace | Name | Description |
|---|---|---|
| autoescape | Force autoescape behavior for this block. | |
| comment | Ignore everything between {% comment %} and {% endcomment %}. |
|
| cycle | Cycle among the given strings each time this tag is encountered. | |
| csrf_token | ||
| debug | Output a whole load of debugging information, including the current context and imported modules. | |
| filter | Filter the contents of the block through variable filters. | |
| firstof | Output the first variable passed that is not False. | |
| for | Loop over each item in an array. | |
| if | Evaluate a variable, and if that variable is "true" (i.e., exists, is not empty, and is not a false boolean value), output the contents of the block: | |
| ifchanged | Check if a value has changed from the last iteration of a loop. | |
| load | Load a custom template tag library into the parser. | |
| lorem | Create random Latin text useful for providing test data in templates. | |
| now | Display the date, formatted according to the given string. | |
| querystring | Add, remove, and change parameters of a QueryDict and return the result as a query string. If the query_dict argument is not provided, default to request.GET. |
|
| regroup | Regroup a list of alike objects by a common attribute. | |
| resetcycle | Reset a cycle tag. | |
| spaceless | Remove whitespace between HTML tags, including tab and newline characters. | |
| templatetag | Output one of the bits used to compose template tags. | |
| url | Return an absolute URL matching the given view with its parameters. | |
| verbatim | Stop the template engine from rendering the contents of this block tag. | |
| widthratio | For creating bar charts and such. Calculate the ratio of a given value to a maximum value, and then apply that ratio to a constant. | |
| with | Add one or more values to the context (inside of this block) for caching and easy access. | |
| block | Define a block that can be overridden by child templates. | |
| extends | Signal that this template extends a parent template. | |
| include | Load a template and render it with the current context. You can pass additional context using keyword arguments. | |
| account | user_display | Example usage:: |
| admin_list | paginator_number | Generate an individual page index link in a paginated list. |
| admin_list | pagination | |
| admin_list | result_list | |
| admin_list | date_hierarchy | |
| admin_list | search_form | |
| admin_list | admin_list_filter | |
| admin_list | admin_actions | |
| admin_list | change_list_object_tools | Display the row of change list object tools. |
| admin_modify | prepopulated_fields_js | |
| admin_modify | submit_row | |
| admin_modify | change_form_object_tools | Display the row of change form object tools. |
| admin_urls | add_preserved_filters | |
| allauth | slot | |
| allauth | element | |
| allauth | setvar | |
| barcode | clean_barcode | Return a 'cleaned' string for encoding into a barcode / qrcode. |
| barcode | qrcode | Return a byte-encoded QR code image. |
| barcode | barcode | Render a 1D barcode. |
| barcode | datamatrix | Render a DataMatrix barcode. |
| cache | cache | This will cache the contents of a template fragment for a given amount of time. |
| djmoney | money_localize | Usage:: |
| feature_flags | flag_enabled | |
| feature_flags | flag_disabled | |
| generic | status_label | Render a status label. |
| generic | display_status_label | Render a status label. |
| i18n | get_available_languages | Store a list of available languages in the context. |
| i18n | get_language_info | Store the language information dictionary for the given language code in a context variable. |
| i18n | get_language_info_list | Store a list of language information dictionaries for the given language codes in a context variable. The language codes can be specified either as a list of strings or a settings.LANGUAGES style list (or any sequence of sequences whose first items are language codes). |
| i18n | get_current_language | Store the current language in the context. |
| i18n | get_current_language_bidi | Store the current language layout in the context. |
| i18n | trans | Mark a string for translation and translate the string for the current language. |
| i18n | translate | Mark a string for translation and translate the string for the current language. |
| i18n | blocktrans | Translate a block of text with parameters. |
| i18n | blocktranslate | Translate a block of text with parameters. |
| i18n | language | Enable the given language just for this block. |
| inventree_extras | define | Shortcut function to overcome the shortcomings of the django templating language. |
| inventree_extras | decimal | Simplified rendering of a decimal number. |
| inventree_extras | render_date | Renders a date object as a string. |
| inventree_extras | str2bool | Convert a string to a boolean value. |
| inventree_extras | to_list | Return the input arguments as list. |
| inventree_extras | inventree_instance_name | Return the InstanceName associated with the current database. |
| inventree_extras | inventree_title | Return the title for the current instance - respecting the settings. |
| inventree_extras | inventree_logo | Return the InvenTree logo, or a custom logo if the user has provided one. |
| inventree_extras | inventree_version | Return InvenTree version string. |
| inventree_extras | inventree_commit_hash | Return InvenTree git commit hash string. |
| inventree_extras | inventree_installer | Return InvenTree package installer string. |
| inventree_extras | inventree_commit_date | Return InvenTree git commit date string. |
| inventree_extras | setting_object | Return a setting object specified by the given key. |
| inventree_extras | settings_value | Return a settings value specified by the given key. |
| inventree_extras | inventree_customize | Return customization values for the user interface. |
| l10n | localize | Force or prevents localization of values. |
| log | get_admin_log | Populate a template variable with the admin log for the given criteria. |
| markdownify | markdownify | |
| mptt_admin | mptt_result_list | Displays the headers and data list together |
| mptt_tags | full_tree_for_model | Populates a template variable with a QuerySet containing the full tree for a given model. |
| mptt_tags | drilldown_tree_for_node | Populates a template variable with the drilldown tree for a given node, optionally counting the number of items associated with its children. |
| mptt_tags | recursetree | Iterates over the nodes in the tree, and renders the contained block for each node. This tag will recursively render children into the template variable {{ children }}. Only one database query is required (children are cached for the whole tree) |
| plugin_extras | plugin_list | List of all installed plugins. |
| plugin_extras | inactive_plugin_list | List of all inactive plugins. |
| plugin_extras | plugin_settings | List of all settings for the plugin. |
| plugin_extras | mixin_enabled | Is the mixin registered and configured in the plugin? |
| plugin_extras | mixin_available | Returns True if there is at least one active plugin which supports the provided mixin. |
| plugin_extras | safe_url | Safe lookup fnc for URLs. |
| report | order_queryset | Order a database queryset based on the provided arguments. |
| report | filter_queryset | Filter a database queryset based on the provided keyword arguments. |
| report | filter_db_model | Filter a database model based on the provided keyword arguments. |
| report | getindex | Return the value contained at the specified index of the list. |
| report | getkey | Perform key lookup in the provided dict object. |
| report | asset | Return fully-qualified path for an upload report asset file. |
| report | uploaded_image | Return raw image data from an 'uploaded' image. |
| report | encode_svg_image | Return a base64-encoded svg image data string. |
| report | part_image | Return a fully-qualified path for a part image. |
| report | parameter | Return a Parameter object for the given part and parameter name. |
| report | part_parameter | Included for backwards compatibility - use 'parameter' tag instead. |
| report | company_image | Return a fully-qualified path for a company image. |
| report | logo_image | Return a fully-qualified path for the logo image. |
| report | internal_link | Make a <a></a> href which points to an InvenTree URL. |
| report | add | Add two numbers (or number like values) together. |
| report | subtract | Subtract one number (or number-like value) from another. |
| report | multiply | Multiply two numbers (or number-like values) together. |
| report | divide | Divide one number (or number-like value) by another. |
| report | modulo | Calculate the modulo of one number (or number-like value) by another. |
| report | render_currency | Render a currency / Money object. |
| report | create_currency | Create a Money object, with the provided amount and currency. |
| report | convert_currency | Convert a Money object to the specified currency. |
| report | render_html_text | Render a text item with some simple html tags. |
| report | format_number | Render a number with optional formatting options. |
| report | format_datetime | Format a datetime object for display. |
| report | format_date | Format a date object for display. |
| report | icon | Render an icon from the icon packs. |
| report | include_icon_fonts | Return the CSS font-face rule for the icon fonts used on the current page (or all). |
| rest_framework | code | |
| rest_framework | form_for_link | |
| rest_framework | render_markdown | |
| rest_framework | get_pagination_html | |
| rest_framework | render_form | |
| rest_framework | render_field | |
| rest_framework | optional_login | Include a login snippet if REST framework's login view is in the URLconf. |
| rest_framework | optional_docs_login | Include a login snippet if REST framework's login view is in the URLconf. |
| rest_framework | optional_logout | Include a logout snippet if REST framework's logout view is in the URLconf. |
| rest_framework | add_query_param | Add a query parameter to the current request url, and return the new url. |
| socialaccount | provider_login_url | {% provider_login_url "facebook" next=bla %} |
| socialaccount | providers_media_js | |
| socialaccount | get_social_accounts | {% get_social_accounts user as accounts %} |
| socialaccount | get_providers | Returns a list of social authentication providers. |
| spa_helper | spa_bundle | Render SPA bundle. |
| spa_helper | spa_settings | Render settings for spa. |
| static | get_static_prefix | Populate a template variable with the static prefix, settings.STATIC_URL. |
| static | get_media_prefix | Populate a template variable with the media prefix, settings.MEDIA_URL. |
| static | static | Join the given path with the STATIC_URL setting. |
| tz | localtime | Force or prevent conversion of datetime objects to local time, regardless of the value of settings.USE_TZ. |
| tz | timezone | Enable a given time zone just for this block. |
| tz | get_current_timezone | Store the name of the current time zone in the context. |
Filters¶
| Namespace | Name | Description |
|---|---|---|
| addslashes | Add slashes before quotes. Useful for escaping strings in CSV, for example. Less useful for escaping JavaScript; use the escapejs filter instead. |
|
| capfirst | Capitalize the first character of the value. | |
| escapejs | Hex encode characters for use in JavaScript strings. | |
| json_script | Output value JSON-encoded, wrapped in a <script type="application/json"> tag (with an optional id). | |
| floatformat | Display a float to a specified number of decimal places. | |
| iriencode | Escape an IRI value for use in a URL. | |
| linenumbers | Display text with line numbers. | |
| lower | Convert a string into all lowercase. | |
| make_list | Return the value turned into a list. | |
| slugify | Convert to ASCII. Convert spaces to hyphens. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace. | |
| stringformat | Format the variable according to the arg, a string formatting specifier. | |
| title | Convert a string into titlecase. | |
| truncatechars | Truncate a string after arg number of characters. |
|
| truncatechars_html | Truncate HTML after arg number of chars. Preserve newlines in the HTML. |
|
| truncatewords | Truncate a string after arg number of words. Remove newlines within the string. |
|
| truncatewords_html | Truncate HTML after arg number of words. Preserve newlines in the HTML. |
|
| upper | Convert a string into all uppercase. | |
| urlencode | Escape a value for use in a URL. | |
| urlize | Convert URLs in plain text into clickable links. | |
| urlizetrunc | Convert URLs into clickable links, truncating URLs to the given character limit, and adding 'rel=nofollow' attribute to discourage spamming. | |
| wordcount | Return the number of words. | |
| wordwrap | Wrap words at arg line length. |
|
| ljust | Left-align the value in a field of a given width. | |
| rjust | Right-align the value in a field of a given width. | |
| center | Center the value in a field of a given width. | |
| cut | Remove all values of arg from the given string. | |
| escape | Mark the value as a string that should be auto-escaped. | |
| escapeseq | An "escape" filter for sequences. Mark each element in the sequence, individually, as a string that should be auto-escaped. Return a list with the results. | |
| force_escape | Escape a string's HTML. Return a new string containing the escaped characters (as opposed to "escape", which marks the content for later possible escaping). | |
| linebreaks | Replace line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (<br>) and a new line followed by a blank line becomes a paragraph break (</p>). |
|
| linebreaksbr | Convert all newlines in a piece of plain text to HTML line breaks (<br>). |
|
| safe | Mark the value as a string that should not be auto-escaped. | |
| safeseq | A "safe" filter for sequences. Mark each element in the sequence, individually, as safe, after converting them to strings. Return a list with the results. | |
| striptags | Strip all [X]HTML tags. | |
| dictsort | Given a list of dicts, return that list sorted by the property given in the argument. | |
| dictsortreversed | Given a list of dicts, return that list sorted in reverse order by the property given in the argument. | |
| first | Return the first item in a list. | |
| join | Join a list with a string, like Python's str.join(list). |
|
| last | Return the last item in a list. | |
| length | Return the length of the value - useful for lists. | |
| random | Return a random item from the list. | |
| slice | Return a slice of the list using the same syntax as Python's list slicing. | |
| unordered_list | Recursively take a self-nested list and return an HTML unordered list -- WITHOUT opening and closing <ul> tags. | |
| add | Add the arg to the value. | |
| get_digit | Given a whole number, return the requested digit of it, where 1 is the right-most digit, 2 is the second-right-most digit, etc. Return the original value for invalid input (if input or argument is not an integer, or if argument is less than 1). Otherwise, output is always an integer. | |
| date | Format a date according to the given format. | |
| time | Format a time according to the given format. | |
| timesince | Format a date as the time since that date (i.e. "4 days, 6 hours"). | |
| timeuntil | Format a date as the time until that date (i.e. "4 days, 6 hours"). | |
| default | If value is unavailable, use given default. | |
| default_if_none | If value is None, use given default. | |
| divisibleby | Return True if the value is divisible by the argument. | |
| yesno | Given a string mapping values for true, false, and (optionally) None, return one of those strings according to the value: | |
| filesizeformat | Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc.). | |
| pluralize | Return a plural suffix if the value is not 1, '1', or an object of length 1. By default, use 's' as the suffix: | |
| phone2numeric | Take a phone number and converts it in to its numerical equivalent. | |
| pprint | A wrapper around pprint.pprint -- for debugging, really. | |
| admin_modify | cell_count | Return the number of cells used in a tabular inline. |
| admin_urls | admin_urlname | |
| admin_urls | admin_urlquote | |
| flags_debug | bool_enabled | |
| flags_debug | conditions_without_bool | |
| flags_debug | required_conditions_without_bool | |
| flags_debug | state_str | Construct a string that describes the current state of the flag |
| humanize | ordinal | Convert an integer to its ordinal as a string. 1 is '1st', 2 is '2nd', 3 is '3rd', etc. Works for any non-negative integer. |
| humanize | intcomma | Convert an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'. |
| humanize | intword | Convert a large integer to a friendly text representation. Works best for numbers over 1 million. For example, 1000000 becomes '1.0 million', 1200000 becomes '1.2 million' and '1200000000' becomes '1.2 billion'. |
| humanize | apnumber | For numbers 1-9, return the number spelled out. Otherwise, return the number. This follows Associated Press style. |
| humanize | naturalday | For date values that are tomorrow, today or yesterday compared to present day return representing string. Otherwise, return a string formatted according to settings.DATE_FORMAT. |
| humanize | naturaltime | For date and time values show how many seconds, minutes, or hours ago compared to current timestamp return representing string. |
| i18n | language_name | |
| i18n | language_name_translated | |
| i18n | language_name_local | |
| i18n | language_bidi | |
| inventree_extras | keyvalue | Access to key of supplied dict. |
| l10n | localize | Force a value to be rendered as a localized value. |
| l10n | unlocalize | Force a value to be rendered as a non-localized value. |
| markdownify | markdownify | |
| mptt_tags | tree_info | Given a list of tree items, produces doubles of a tree item and a dict containing information about the tree structure around the item, with the following contents: |
| mptt_tags | tree_path | Creates a tree path represented by a list of items by joining the items with a separator. |
| mptt_tags | cache_tree_children | Alias to mptt.utils.get_cached_trees. |
| rest_framework | with_location | |
| rest_framework | as_string | |
| rest_framework | as_list_of_strings | |
| rest_framework | add_class | https://stackoverflow.com/questions/4124220/django-adding-css-classes-when-rendering-form-fields-in-a-template |
| rest_framework | format_value | |
| rest_framework | items | Simple filter to return the items of the dict. Useful when the dict may have a key 'items' which is resolved first in Django template dot-notation lookup. See issue #4931 Also see: https://stackoverflow.com/questions/15416662/django-template-loop-over-dictionary-items-with-items-as-key |
| rest_framework | data | Simple filter to access data attribute of object, specifically coreapi.Document. |
| rest_framework | schema_links | Recursively find every link in a schema, even nested. |
| rest_framework | add_nested_class | |
| tz | localtime | Convert a datetime to local time in the active time zone. |
| tz | utc | Convert a datetime to UTC. |
| tz | timezone | Convert a datetime to local time in a given time zone. |