So I have created a custom form for my attribute table in QGIS using the drag and drop designer option. I also have an external python init function that I imported. Now Let's say I create a new Feature. After I create the feature the custom form pops up and my python file checks if a specific attribute of the feature is not defined(or is NULL). If it is NULL or not defined I set the attribute. My code for this part looks like this:

if feature["name"] is None:
   feature.setAttribute("name", "Max")

Until now everything works. My problem is now that if I open the attribute table in qgis I always get an KeyError, but the attribute was set successfully. The KeyError look like this KeyError: 'name'. It might be hard to understand but I can't describe it better. Does anyone know what I am doing wrong?

2 Answers 2


I solved my problem with these two line:

fields = layer.fields()

What I did was give the feature all fields that exist in the layer, because sometimes some features don't get all of them. That's what I think was the problem.


It's been a few years, but i ran in a similar problem and i wanted to share my solution.

It seems, that the error occurs because opening the attribute table triggers the init function, but the feature is 'empty'. It's not None, but has no fields. That's why you get a key error.

My code should only be executed, when i create a new feature (FeatureForm) but not when i open the attribute table. I tried many things until i realized, that the attribute table is a window, the feature form is not. So you can add a guard clause at the beginning of the init function:

def formOpen(dialog, layer, feature):
    if dialog.isWindow():
    <code for the FeatureForm>

Hope this helps some other people.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.