[GIS] AttributeError: ‘NoneType’ object has no attribute ‘dataProvider’

attribute-tablepyqgispythonqgis

I want to add new column to attribute table of vector layer via Python console. I'm trying to do this following instructions from http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/vector.html.
But while defying caps

caps = layer.dataProvider().capabilities()

I'm getting error:

AttributeError: 'NoneType' object has no attribute 'dataProvider'

I've found some solutions referring to setting up QGIS Python environment correctly. (Getting dataProvider from vector layer outside QGIS). But this solution crash my QGIS.

Any idea what should I do to access (?) (or rather 'get?') dataProvider?

Best Answer

You could use the following to add a new field and determining its type:

from PyQt4.QtCore import *

layer = qgis.utils.iface.activeLayer()
layer.startEditing()
layer.dataProvider().addAttributes( [ QgsField("Name", QVariant.String) ] )
layer.commitChanges()
Related Question