Skip to content

Context Variables

Context Variables

Context variables are provided to each template when it is rendered. The available context variables depend on the model type for which the template is being rendered.

Global Context

In addition to the model-specific context variables, the following global context variables are available to all templates:

Variable Description
base_url The base URL for the InvenTree instance
date Current date, represented as a Python datetime.date object
datetime Current datetime, represented as a Python datetime object
template The report template instance which is being rendered against
template_description Description of the report template
template_name Name of the report template
template_revision Revision of the report template
user User who made the request to render the template

Return base context data (available to all templates).

Source code in src/backend/InvenTree/report/models.py
244
245
246
247
248
249
250
251
252
253
254
255
def base_context(self, request=None):
    """Return base context data (available to all templates)."""
    return {
        'base_url': get_base_url(request=request),
        'date': InvenTree.helpers.current_date(),
        'datetime': InvenTree.helpers.current_time(),
        'template': self,
        'template_description': self.description,
        'template_name': self.name,
        'template_revision': self.revision,
        'user': request.user if request else None,
    }

Report Context

In addition to the global context, all report templates have access to the following context variables:

Variable Description
page_size The page size of the report
landscape Boolean value, True if the report is in landscape mode

Note that custom plugins may also add additional context variables to the report context.

Supply context data to the report template for rendering.

Source code in src/backend/InvenTree/report/models.py
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
def get_context(self, instance, request=None, **kwargs):
    """Supply context data to the report template for rendering."""
    context = {
        **super().get_context(instance, request),
        'page_size': self.get_report_size(),
        'landscape': self.landscape,
    }

    # Pass the context through to the plugin registry for any additional information
    for plugin in registry.with_mixin('report'):
        try:
            plugin.add_report_context(self, instance, request, context)
        except Exception:
            InvenTree.exceptions.log_error(
                f'plugins.{plugin.slug}.add_report_context'
            )

    return context

Label Context

In addition to the global context, all label templates have access to the following context variables:

Variable Description
width The width of the label (in mm)
height The height of the label (in mm)

Note that custom plugins may also add additional context variables to the label context.

Supply context data to the label template for rendering.

Source code in src/backend/InvenTree/report/models.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
def get_context(self, instance, request=None, **kwargs):
    """Supply context data to the label template for rendering."""
    context = {
        **super().get_context(instance, request, **kwargs),
        'width': self.width,
        'height': self.height,
    }

    if kwargs.pop('insert_page_style', True):
        context['page_style'] = self.generate_page_style()

    # Pass the context through to any registered plugins
    plugins = registry.with_mixin('report')

    for plugin in plugins:
        # Let each plugin add its own context data
        plugin.add_label_context(self, instance, request, context)

    return context

Template Types

Templates (whether for generating reports or labels) are rendered against a particular "model" type. The following model types are supported, and can have templates renderer against them:

Model Type Description
build A Build Order instance
buildline A Build Order Line Item instance
salesorder A Sales Order instance
returnorder A Return Order instance
purchaseorder A Purchase Order instance
stockitem A StockItem instance
stocklocation A StockLocation instance
part A Part instance

Build Order

When printing a report or label against a Build Order object, the following context variables are available:

Variable Description
bom_items Query set of all BuildItem objects associated with the BuildOrder
build The BuildOrder instance itself
build_outputs Query set of all BuildItem objects associated with the BuildOrder
line_items Query set of all build line items associated with the BuildOrder
part The Part object which is being assembled in the build order
quantity The total quantity of the part being assembled
reference The reference field of the BuildOrder
title The title field of the BuildOrder

Generate custom report context data.

Source code in src/backend/InvenTree/build/models.py
182
183
184
185
186
187
188
189
190
191
192
193
194
def report_context(self) -> dict:
    """Generate custom report context data."""

    return {
        'bom_items': self.part.get_bom_items(),
        'build': self,
        'build_outputs': self.build_outputs.all(),
        'line_items': self.build_lines.all(),
        'part': self.part,
        'quantity': self.quantity,
        'reference': self.reference,
        'title': str(self)
    }

Build Line

When printing a report or label against a BuildOrderLineItem object, the following context variables are available:

Variable Description
allocated_quantity The quantity of the part which has been allocated to this build
allocations A query set of all StockItem objects which have been allocated to this build line
bom_item The BomItem associated with this line item
build The BuildOrder instance associated with this line item
build_line The build line instance itself
part The sub-part (component) associated with the linked BomItem instance
quantity The quantity required for this line item

Generate custom report context for this BuildLine object.

Source code in src/backend/InvenTree/build/models.py
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
def report_context(self):
    """Generate custom report context for this BuildLine object."""

    return {
        'allocated_quantity': self.allocated_quantity,
        'allocations': self.allocations,
        'bom_item': self.bom_item,
        'build': self.build,
        'build_line': self,
        'part': self.bom_item.sub_part,
        'quantity': self.quantity,
    }

Sales Order

When printing a report or label against a SalesOrder object, the following context variables are available:

Variable Description
customer The customer object associated with the SalesOrder
description The description field of the SalesOrder
extra_lines Query set of all extra lines associated with the SalesOrder
lines Query set of all line items associated with the SalesOrder
order The SalesOrder instance itself
reference The reference field of the SalesOrder
title The title (string representation) of the SalesOrder

Generate context data for the reporting interface.

Source code in src/backend/InvenTree/order/models.py
250
251
252
253
254
255
256
257
258
259
def report_context(self):
    """Generate context data for the reporting interface."""
    return {
        'description': self.description,
        'extra_lines': self.extra_lines,
        'lines': self.lines,
        'order': self,
        'reference': self.reference,
        'title': str(self),
    }

Return Order

When printing a report or label against a ReturnOrder object, the following context variables are available:

Variable Description
customer The customer object associated with the ReturnOrder
description The description field of the ReturnOrder
extra_lines Query set of all extra lines associated with the ReturnOrder
lines Query set of all line items associated with the ReturnOrder
order The ReturnOrder instance itself
reference The reference field of the ReturnOrder
title The title (string representation) of the ReturnOrder

Purchase Order

When printing a report or label against a PurchaseOrder object, the following context variables are available:

Variable Description
description The description field of the PurchaseOrder
extra_lines Query set of all extra lines associated with the PurchaseOrder
lines Query set of all line items associated with the PurchaseOrder
order The PurchaseOrder instance itself
reference The reference field of the PurchaseOrder
supplier The supplier object associated with the PurchaseOrder
title The title (string representation) of the PurchaseOrder

Stock Item

When printing a report or label against a StockItem object, the following context variables are available:

Variable Description
barcode_data Generated barcode data for the StockItem
barcode_hash Hash of the barcode data
batch The batch code for the StockItem
child_items Query set of all StockItem objects which are children of this StockItem
ipn The IPN (internal part number) of the associated Part
installed_items Query set of all StockItem objects which are installed in this StockItem
item The StockItem object itself
name The name of the associated Part
part The Part object which is associated with the StockItem
qr_data Generated QR code data for the StockItem
qr_url Generated URL for embedding in a QR code
parameters Dict object containing the parameters associated with the base Part
quantity The quantity of the StockItem
result_list FLattened list of TestResult data associated with the stock item
results Dict object of TestResult data associated with the StockItem
serial The serial number of the StockItem
stock_item The StockItem object itself (shadow of 'item')
tests Dict object of TestResult data associated with the StockItem (shadow of 'results')
test_keys List of test keys associated with the StockItem
test_template_list List of test templates associated with the StockItem
test_templates Dict object of test templates associated with the StockItem

Generate custom report context data for this StockItem.

Source code in src/backend/InvenTree/stock/models.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
def report_context(self):
    """Generate custom report context data for this StockItem."""
    return {
        'barcode_data': self.barcode_data,
        'barcode_hash': self.barcode_hash,
        'batch': self.batch,
        'child_items': self.get_children(),
        'ipn': self.part.IPN,
        'installed_items': self.get_installed_items(cascade=True),
        'item': self,
        'name': self.part.full_name,
        'part': self.part,
        'qr_data': self.barcode,
        'qr_url': self.get_absolute_url(),
        'parameters': self.part.parameters_map(),
        'quantity': InvenTree.helpers.normalize(self.quantity),
        'result_list': self.testResultList(include_installed=True),
        'results': self.testResultMap(include_installed=True),
        'serial': self.serial,
        'stock_item': self,
        'tests': self.testResultMap(),
        'test_keys': self.get_test_keys(),
        'test_template_list': self.part.getTestTemplates(),
        'test_templates': self.part.getTestTemplateMap(),
    }

Stock Location

When printing a report or label against a StockLocation object, the following context variables are available:

Variable Description
location The StockLocation object itself
qr_data Formatted QR code data for the StockLocation
parent The parent StockLocation object
stock_location The StockLocation object itself (shadow of 'location')
stock_items Query set of all StockItem objects which are located in the StockLocation

Return report context data for this StockLocation.

Source code in src/backend/InvenTree/stock/models.py
156
157
158
159
160
161
162
163
164
def report_context(self):
    """Return report context data for this StockLocation."""
    return {
        'location': self,
        'qr_data': self.barcode,
        'parent': self.parent,
        'stock_location': self,
        'stock_items': self.get_stock_items(),
    }

Part

When printing a report or label against a Part object, the following context variables are available:

Variable Description
bom_items Query set of all BomItem objects associated with the Part
category The PartCategory object associated with the Part
description The description field of the Part
IPN The IPN (internal part number) of the Part
name The name of the Part
parameters Dict object containing the parameters associated with the Part
part The Part object itself
qr_data Formatted QR code data for the Part
qr_url Generated URL for embedding in a QR code
revision The revision of the Part
test_template_list List of test templates associated with the Part
test_templates Dict object of test templates associated with the Part

Return custom report context information.

Source code in src/backend/InvenTree/part/models.py
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
def report_context(self):
    """Return custom report context information."""
    return {
        'bom_items': self.get_bom_items(),
        'category': self.category,
        'description': self.description,
        'IPN': self.IPN,
        'name': self.name,
        'parameters': self.parameters_map(),
        'part': self,
        'qr_data': self.barcode,
        'qr_url': self.get_absolute_url(),
        'revision': self.revision,
        'test_template_list': self.getTestTemplates(),
        'test_templates': self.getTestTemplateMap(),
    }

Model Variables

Additional to the context variables provided directly to each template, each model type has a number of attributes and methods which can be accessedd via the template.

For each model type, a subset of the most commonly used attributes are listed below. For a full list of attributes and methods, refer to the source code for the particular model type.

Parts

Part

Each part object has access to a lot of context variables about the part. The following context variables are provided when accessing a Part object from within the template.

Variable Description
name Brief name for this part
full_name Full name for this part (including IPN, if not null and including variant, if not null)
variant Optional variant number for this part - Must be unique for the part name
category The PartCategory object to which this part belongs
description Longer form description of the part
keywords Optional keywords for improving part search results
IPN Internal part number (optional)
revision Part revision
is_template If True, this part is a 'template' part
link Link to an external page with more information about this part (e.g. internal Wiki)
image Image of this part
default_location The default StockLocation object where the item is normally stored (may be null)
default_supplier The default SupplierPart which should be used to procure and stock this part
default_expiry The default expiry duration for any StockItem instances of this part
minimum_stock Minimum preferred quantity to keep in stock
units Units of measure for this part (default='pcs')
salable Can this part be sold to customers?
assembly Can this part be build from other parts?
component Can this part be used to make other parts?
purchaseable Can this part be purchased from suppliers?
trackable Trackable parts can have unique serial numbers assigned, etc, etc
active Is this part active? Parts are deactivated instead of being deleted
virtual Is this part "virtual"? e.g. a software product or similar
notes Additional notes field for this part
creation_date Date that this part was added to the database
creation_user User who added this part to the database
responsible User who is responsible for this part (optional)
starred Whether the part is starred or not
disabled Whether the part is disabled or not
total_stock The total amount in stock
quantity_being_built The amount being built
required_build_order_quantity The amount required for build orders
allocated_build_order_quantity The amount allocated for build orders
build_order_allocations Query set with all build order allocations for that part
required_sales_order_quantity The amount required for sales orders
allocated_sales_order_quantity The amount allocated for sales orders
available Whether the part is available or not
on_order The amount that are on order
required The total amount required for build orders and sales orders
allocated The total amount allocated for build orders and sales orders

Part Category

Variable Description
name Name of this category
parent Parent category
default_location Default StockLocation object for parts in this category or child categories
default_keywords Default keywords for parts created in this category

Stock

StockItem

Variable Description
parent Link to another StockItem from which this StockItem was created
uid Field containing a unique-id which is mapped to a third-party identifier (e.g. a barcode)
part Link to the master abstract Part that this StockItem is an instance of
supplier_part Link to a specific SupplierPart (optional)
location The StockLocation Where this StockItem is located
quantity Number of stocked units
batch Batch number for this StockItem
serial Unique serial number for this StockItem
link Optional URL to link to external resource
updated Date that this stock item was last updated (auto)
expiry_date Expiry date of the StockItem (optional)
stocktake_date Date of last stocktake for this item
stocktake_user User that performed the most recent stocktake
review_needed Flag if StockItem needs review
delete_on_deplete If True, StockItem will be deleted when the stock level gets to zero
status Status of this StockItem (ref: InvenTree.status_codes.StockStatus)
status_label Textual representation of the status e.g. "OK"
notes Extra notes field
build Link to a Build (if this stock item was created from a build)
is_building Boolean field indicating if this stock item is currently being built (or is "in production")
purchase_order Link to a PurchaseOrder (if this stock item was created from a PurchaseOrder)
infinite If True this StockItem can never be exhausted
sales_order Link to a SalesOrder object (if the StockItem has been assigned to a SalesOrder)
purchase_price The unit purchase price for this StockItem - this is the unit price at time of purchase (if this item was purchased from an external supplier)
packaging Description of how the StockItem is packaged (e.g. "reel", "loose", "tape" etc)

StockLocation

Variable Description
barcode Brief payload data (e.g. for labels). Example: {"stocklocation": 826} where 826 is the primary key
description The description of the location
icon The name of the icon if set, e.g. fas fa-warehouse
item_count Simply returns the number of stock items in this location
name The name of the location. This is only the name of this location, not the path
owner The owner of the location if it has one. The owner can only be assigned in the admin interface
parent The parent location. Returns None if it is already the top most one
path A queryset of locations that contains the hierarchy starting from the top most parent
pathstring A string that contains all names of the path separated by slashes e.g. A/B/C
structural True if the location is structural

Suppliers

Company

Variable Description
name Name of the company
description Longer form description
website URL for the company website
primary_address Address object that is marked as primary address
address String format of the primary address
contact Contact Name
phone Contact phone number
email Contact email address
link A second URL to the company (Actually only accessible in the admin interface)
notes Extra notes about the company (Actually only accessible in the admin interface)
is_customer Boolean value, is this company a customer
is_supplier Boolean value, is this company a supplier
is_manufacturer Boolean value, is this company a manufacturer
currency_code Default currency for the company
parts Query set with all parts that the company supplies

Address

Variable Description
line1 First line of the postal address
line2 Second line of the postal address
postal_code ZIP code of the city
postal_city City name
country Country name

Contact

Variable Description
company Company object where the contact belongs to
name First and second name of the contact
phone Phone number
email Email address
role Role of the contact

SupplierPart

Variable Description
part Link to the master Part (Obsolete)
source_item The sourcing StockItem linked to this SupplierPart instance
supplier Company that supplies this part
SKU Stock keeping unit (supplier part number)
link Link to external website for this supplier part
description Descriptive notes field
note Longer form note field
base_cost Base charge added to order independent of quantity e.g. "Reeling Fee"
multiple Multiple that the part is provided in
lead_time Supplier lead time
packaging packaging that the part is supplied in, e.g. "Reel"
pretty_name The IPN, supplier name, supplier SKU and (if not null) manufacturer string joined by |. Ex. P00037 | Company | 000021
unit_pricing The price for one unit.
price_breaks Return the associated price breaks in the correct order
has_price_breaks Whether this SupplierPart has price breaks
manufacturer_string Format a MPN string for this SupplierPart. Concatenates manufacture name and part number.

Orders

Purchase Order

TODO

This section is incomplete

SalesOrder

A Sales Order object has the following context variables available.

Variable Description
customer An object with information about the customer
description The order description
lines The lines in the Sales Order
reference The reference number

Return Order

A Return Order object has the following context variables available.

Variable Description
customer An object with information about the customer
description The order description
lines The lines in the Sales Order
reference The reference number

User

Variable Description
username the username of the user
fist_name The first name of the user
last_name The last name of the user
email The email address of the user
pk The primary key of the user