Call Custom python function in jinja

A bit outdated, but I managed to solve this one with help from another post, here are point to point instructions:

It’s necessary to whitelist your function so it can be called successfully from a custom Print Format.

1.- Develop your function in any python file ( .py ) within your custom app, and add the following decorator above the function:

@frappe.whitelist()

2.- If the file where you defined the function is /apps/your-app/your-app/your_module.py and the function is called my_function () the route that you will use is this: your_app.your_module.my_function

3.- Add the following to hooks.py

jenv = {
    “methods”: [
        “my_function:your_app.your_module.my_function”
    ]
}

Please note that the definition to pass your defined Python function to the Jinja environment is defined by the following structure:

[virtual_environment_desired_function_name]:[route_and_name_of_python_function]Preformatted text

4.- On your terminal, execute the following commands:

bench restart
bench migrate

Even though bench migrate is not required, some reports exist about it improving the desired functionality outcome.

5.- On the custom Print Format where you wish to access your function, execute it in the following manner:

{{ virtual_environment_desired_function_name() }}

You may pass arguments to it, and you will receive the returned results (if such is the purpose of your function)

Main Source: Call your own functions in Frappe

8 Likes