5

The following code updates the value of the field ("name") in the console and shows the result but the actual attribute table does not get updated. Can anybody suggest the error in the code?

layer = iface.activeLayer()
selected_feature = layer.selectedFeatures()
layer.startEditing()
for feature in selected_feature:
 feature["name"] = "Test name"
layer.commitChanges()
Taras
35.8k5 gold badges77 silver badges152 bronze badges
asked Mar 28, 2019 at 5:08

2 Answers 2

9

You need to update the layer with the new feature values using:

layer.updateFeature(feature)

So it should look something like:

layer = iface.activeLayer()
selected_feature = layer.selectedFeatures()
layer.startEditing()
for feature in selected_feature:
 feature["name"] = "Test name"
 layer.updateFeature(feature)
layer.commitChanges()

Or shorten it slightly by editing and committing the changes in one go using with edit():

layer = iface.activeLayer()
selected_feature = layer.selectedFeatures()
with edit(layer):
 for feature in selected_feature:
 feature["name"] = "Test name"
 layer.updateFeature(feature)
Taras
35.8k5 gold badges77 silver badges152 bronze badges
answered Mar 28, 2019 at 10:50
5
  • @BipinThapaliya - Most welcome, glad it helped :) Commented Mar 29, 2019 at 11:20
  • 1
    Not working for me .Tried both of these versions. I am exhausted ;( Commented Aug 1, 2019 at 12:41
  • @ChetanVashisth - Post a question with what you tried and hopefully people will respond :) Commented Aug 1, 2019 at 12:43
  • I have just tried your code above and its not working and i just want to update a field in the attribute table. So i thought i do not have to ask a question for that.. :) Commented Aug 1, 2019 at 12:45
  • I'm getting a NameError 'edit' is not defined... Commented Jul 22, 2020 at 13:42
-1

QgsProject.instance().reloadAllLayers() worked for me on QGIS 3.10.

Kadir Şahbaz
78.6k57 gold badges260 silver badges407 bronze badges
answered Apr 9, 2021 at 13:19
2
  • Worked for me on QGIS 3.10 Commented Apr 9, 2021 at 13:20
  • 1
    Welcome to GIS SE! As a new user please take the tour. A good answer should include details about how to use your suggestion and info about what it does. Please edit your answer to add additional info. Commented Apr 9, 2021 at 15:32

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.