Get the components names of a form

Apparently, there’s not a straightforward way of getting the names of a form’s components.

Here is a function that does this should anyone need it:

def get_component_names(form):
  component_names = []
  # get the form's components (python objects)
  components = form.get_components()
  
  for attr_name in dir(form):
    attr = getattr(form, attr_name)
    # check if the attribute is one ofthe form's components
    if attr in components:
      component_names.append(attr_name)
  return component_names

To use it you just have to pass the form as an argument (you should pass self if you use it in one of the form’s methods like the __init__).

The limitation is that it only gives you the names of the top-level components, as form.get_components() returns only those.

2 Likes