PyQGIS – Auto Populating Attributes Without Edit Form in PyQGIS

pyqgisqgis-3qgis-plugins

In my plugin, the user can go into add feature mode:

    self.poly_layer.startEditing()
    iface.actionAddFeature().trigger()

And I can suppress the edit form from popping up by doing this:

    formConfig = self.poly_layer.editFormConfig()
    formConfig.setSuppress(QgsEditFormConfig.SuppressOn)
    self.poly_layer.setEditFormConfig(formConfig)

And then the user can draw out a polygon (this is a polygon layer).
I have connected the feature added to a custom function:

self.poly_layer.featureAdded.connect(self.feature_added)

and in this function I can do something like this:

def feature_added(self):
    fields = {
        'target_geometry_set_id': self.poly_set_id,
        'target_geometry_type': 'Polygon',
        'target_geometry_source': 'qgis',
        'target_geometry_last_modified_by': os.getlogin()}
    for field in fields.keys():
        field_idx = self.poly_layer.fields().indexOf(field)
        self.poly_layer.changeAttributeValue(self.poly_features[self.current_selection_poly].id(), field_idx, fields[field])
    self.poly_layer.commitChanges()

However when a feature is completed I get an error that the table cannot be updated (this is a postgres layer with some columns requiring non Null values) because of Null values. It seems it does not get to my feature added function before it tries to update table.

How can I auto add these attributes to a new feature so the user does not have to fill in edit form every time?

Best Answer

Based on my answer here I was able to get this working by using setDefaultValueDefinition instead of changeattributevalue.