I'm trying to create new features in an existing vector layer and I want to display the attribute form so the user can fill the attributes data. I successfully managed to show attribute form and users can add attributes in it. But while displaying the form, if user cancels the modification, still new feature is getting added in my layer. Please suggest, how i can avoid this scenario. Please check my code below. { layer = iface.activeLayer() if layer.isEditable(): feat = QgsFeature() feat.setGeometry(geom) feat.setFields(layer.fields()) attr=iface.openFeatureForm(layer, feat) }


You can use an edit command buffer. The following works for me in the Python console in QGIS 3.4:

            layer = iface.activeLayer()
            if layer.isEditable():
                layer.beginEditCommand('Add Snapped Feature')
                feat = QgsFeature(layer.fields(), layer.featureCount())
                tbl = iface.openFeatureForm(layer, feat)
                if tbl == True:
                elif tbl == False:

You can find out more from the PyQGIS Developer Cookbook.

Note: I understand that it is discouraged to mix layer and data provider editing methods however, when I tried:


I got the following error when saving layer edits after accepting the feature form:

Feature 2 for attribute update not found.

enter image description here

I assume this is because the feature has not been added to the data provider because, when I change the line to:


I don't get any error.

Perhaps someone else can explain the reason for this or suggest a correction but, as I said, the code block above works for me.

Also: see your other question related to this code in a plugin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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