I try to develop a plugin to add postgis layers to qgis from a plugin as part of learning python.

The code for adding a postgis layer is taken from the cookbook and work fine if I run it from the python console within qgis (If button OK is pressed in dialog box result == 1 and should add my layer to qgis).

But if I run it from my plugin it throws the message NameError: name 'QgsDataSourceURI' is not defined. Why do I get that error running it from the plugin?

Is there a difference how I add a layer from a plugin/inside a function vs from the python console?

 def run(self):

        # show the dialog
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result == 1:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            uri = QgsDataSourceURI()
            uri.setConnection("localhost", "5432", "test", "postgres", "postgres")
            uri.setDataSource ("basic", "cities", "geom")
            # Defining the layer name and layer type for QGIS?
            vlayer=QgsVectorLayer (uri .uri() ,"cities","postgres")
  • I'm trying to use your pattern to add PostGIS layer in python console QGIS but unsuccessfully - "NameError: name 'self' is not defined"( . Do you mind telling me please what's wrong? What self mean (I'm not very good in python). Here is my code gis.stackexchange.com/questions/245985/… – Jane Jul 1 '17 at 9:57

Because you need to import Python classes before using them. Just write this in the heading of that file:

from qgis.core import QgsDataSourceURI

It's different in the QGIS Python Console because it automatically loads QGIS classes when it's opened.

Note that if you haven't imported the QgsVectorLayer class yet, you'll get a similar error. Instead of adding a new line, you can list the classes you would like to import from qgis.core library, this way:

from qgis.core import QgsVectorLayer, QgsDataSourceURI
  • 2
    Sorry for the late reply i just had opportunity to try it out and it worked great! Also thank you for explaining how it is possible to list classes from one library, that was also new to me. Best Regards – geogrow Jan 4 '16 at 7:36
  • In QGIS 3, it is renamed to QgsDataSourceUri. – Jay Cummins Dec 7 '18 at 15:01

Your Answer

