TemplateError 'UndefinedError'

Hi,
I've been losing my mind for days with the following templates:
every time I restart Home Assistant, the following errors appear; however, I see that the sensor is counting correctly:
I'm reporting the template code and the errors it reports below:


template:

  • sensor:
    • name: “consumo_netto_pdc”
      unique_id: “consumo netto pdc”
      unit_of_measurement: “Wh”
      device_class: “energy”
      state_class: “total_increasing”
      state: >
      {% set produzione = states(‘sensor.potenza_prodotta_fotovoltaico_realtime_watt’) | float(0) %}
      {% set consumo = states(‘sensor.power_pdc’) | float(0) %}
      {{ [0, consumo - produzione] | max }}
      attributes:
      produzione: “{{ produzione }}”
      consumo: “{{ consumo }}”
      differenza: “{{ consumo - produzione }}”
Registratore: homeassistant.components.template.template_entity
Fonte: components/template/template_entity.py:215
Integrazione: Template ([documentazione](https://www.home-assistant.io/integrations/template), [problemi](https://github.com/home-assistant/core/issues?q=is%3Aissue+is%3Aopen+label%3A%22integration%3A+template%22))
Prima occorrenza: 08:33:48 (1 occorrenza)
Ultimo accesso: 08:33:48

TemplateError('UndefinedError: 'consumo' is undefined') while processing template 'Template<template=({{ consumo - produzione }}) renders=4>' for attribute 'differenza' in entity 'sensor.consumo_netto_pdc'

Error while processing template: Template<template=({{ consumo - produzione }}) renders=2>

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 644, in async_render
    render_result = _render_with_context(self.template, compiled, **kwargs)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 2969, in _render_with_context
    return template.render(**kwargs)
           ~~~~~~~~~~~~~~~^^^^^^^^^^
  File "/usr/local/lib/python3.13/site-packages/jinja2/environment.py", line 1295, in render
    self.environment.handle_exception()
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^
  File "/usr/local/lib/python3.13/site-packages/jinja2/environment.py", line 942, in handle_exception
    raise rewrite_traceback_stack(source=source)
  File "<template>", line 1, in top-level template code
jinja2.exceptions.UndefinedError: 'consumo' is undefined

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 761, in async_render_to_info
    render_info._result = self.async_render(  # noqa: SLF001
                          ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
        variables, strict=strict, log_fn=log_fn, **kwargs
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 646, in async_render
    raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: UndefinedError: 'consumo' is undefined

thanks for your help.Preformatted text

Hi, please next time put your yaml in a </> code block, this is impossible to read or check. But from what I can see: jinja variables you define when determining state do not carry over to the attributes. You have to define them there again.

template:
  - sensor:
      - name: "consumo_netto_pdc"
        unique_id: "consumo netto pdc"
        unit_of_measurement: "Wh"
        device_class: "energy"
        state_class: "total_increasing"
        state: >
          {% set produzione = states('sensor.potenza_prodotta_fotovoltaico_realtime_watt') | float(0) %}
          {% set consumo = states('sensor.power_pdc') | float(0) %}
          {{ [0, consumo - produzione] | max }}
        attributes:
          produzione: "{{ produzione }}"
          consumo: "{{ consumo }}"
          differenza: "{{ consumo - produzione }}"

thanks for the quick reply.
this is exactly what I can’t understand and solve.
I hope I formatted the yaml code correctly.
thanks

Hello,

when system is starting a sensor value is not present so you get the error, maybe?
I did not understand if it works after restart or not?

I confirm, after the reboot it works, the calculation is performed correctly.

Hi,
for me a similar template gives me this error at restart because while is trying to calculate the template the sensor used is not available yet.
I have looked around as well and found some expanation and it seems to be normal.
I am not an expert so take it as a suggestion.

I believe availability condition on the template may solve it:

As I said, the variables in jinja need to be defined again in the attributes. They only live as long as the one template string is. Currently there is no way to define variables at yaml level that apply to the whole template sensor.

template:
  - sensor:
      - name: "consumo_netto_pdc"
        unique_id: "consumo netto pdc"
        unit_of_measurement: "Wh"
        device_class: "energy"
        state_class: "total_increasing"
        state: >
          {% set produzione = states('sensor.potenza_prodotta_fotovoltaico_realtime_watt') | float(0) %}
          {% set consumo = states('sensor.power_pdc') | float(0) %}
          {{ [0, consumo - produzione] | max }}
        attributes:
          produzione: >
            {% set produzione = states('sensor.potenza_prodotta_fotovoltaico_realtime_watt') | float(0) %}
            {{ produzione }}
          consumo: >
            {% set consumo = states('sensor.power_pdc') | float(0) %}
            {{ consumo }}
          differenza: > 
            {% set produzione = states('sensor.potenza_prodotta_fotovoltaico_realtime_watt') | float(0) %}
            {% set consumo = states('sensor.power_pdc') | float(0) %}
            {{ consumo - produzione }}

I did it this as close to possible to demonstrate what was wrong, you can of course eliminate the variables if you directly output what is in it.

Thank you, now I understand better.
you were very kind.

1 Like

The suggestion above to put in an availability template is also a good idea, but solves a different problem:

      availability: >
        has_value('sensor.potenza_prodotta_fotovoltaico_realtime_watt')
        and has_value('sensor.power_pdc')

Adding this makes sure the sensor is unavailable if one of the two sesnors needed for the calculation is unavailable. If you do not do that, the original sensor will assume that sensor is 0, giving calculted values that are wrong.

sorry where should it be added at the end of the code? thanks

I added the code snippet at the end of the previous one and the calculation values ​​are wrong. Basically it starts calculating everything wrong.

The availability template can be placed anywhere between the other fields or at the bottom, as long as the indenting is correct, the available must start in the same colums as name, state, etc.

An availability template does not change the calculation, so it is very unlikely the vrong values were caused by it. It is more likely the values were wrong because one of the source entities was unavailable. If you indented the lines wrong, it might have stopped HA for loading other templates.

Great thanks for the timely answers.
I would like to take advantage of your expertise and kindness.
unit_of_measurement: “Wh”
can I indicate kWh in the unit_of_measurement? without creating incorrect calculations in daily and monthly consumption. thanks again

Probably not, the measurements would be off by a thousand

If the source is in Wh and you want to you change the unit of measurement to kWh in the template, then you need to divide the result by 1000 in your template too:

          {{ (consumo - produzione) / 1000 }}

The history will have the wrong value and unit, so it will mess with history. Statistics will have errors until you fix them by deleting history or change the unit of measurement for all values. Neither is what you want if you want to keep history.

But you can change the displayed unit of measurement via the UI.