Is it possible to get login username from a current PostgreSQL layer connection in QGIS?

My goal is to automatically populate new objects in a layer with an editor login username (not @user_account_name or @user_full_name, because they are not related to a postgres connection).


I solved the problem by writing a custom expression function:

from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='Custom')
def get_username(feature, parent, context):
    layer_name = context.variable('layer_name')
    layer = QgsProject.instance().mapLayersByName(layer_name)[0]
    username = QgsDataSourceUri(layer.dataProvider().dataSourceUri()).username()
    return username

now I can use a custom get_username() function in expression from

  • 1
    That's great, actually, and there was a question a few weeks ago where I suggested using just this same method, though don't know how to write such functions! – DPSSpatial Jul 16 '18 at 15:48

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.