Getting current user in data bindings

I have some buttons that I want to be visible or invisible depending on who the current user is. My first approach was to use a data binding to the visible property. This is in a button that’s on a row of a data grid.

That first button worked wonderfully, with this code bound to the visible property:

len(self.item['players']) > 1 and anvil.users.get_user() == self.item['owner']

Then I added a second button and bound this to its visible property:

len(self.item['players']) < self.item['max_players'] and not anvil.users.get_user() in self.item['players']

That button gives an error when I run the app:

name 'anvil' is not defined

So I played around to try to work out what the difference was between the two bindings. I can confirm that something as simple as this fails with the same error message:

anvil.users.get_user()

But, if I copy my original binding from the first button, it doesn’t generate an error. Does anyone have any ideas what might be going on? What’s special about that first binding that causes it to work, when everything else I try fails? Should I be able to use anvil.users.get_user() in the way that I’m trying inside a data binding?

Hello jshaffstall,
I can’t notice any particular difference between the two expressions.
Have you tried to evaluate that expression in a function’s code just to be sure it works out correctly in a more “standard” environment?
Can you share a sample app to let us test it?

Data Bindings only have access to attributes of self. So if you want to access the current user, you need to create a function to expose anvil.users.get_user():

class Form1(Form1Template):
  # ...
  def get_user(self):
    return anvil.users.get_user()

Then your data binding can be

len(self.item['players']) < self.item['max_players'] and not self.get_user() in self.item['players']

I think it’s working for you in your first example because len(self.item['players']) > 1 is always True when you’re testing it. Python doesn’t evaluate parts of boolean expressions it doesn’t need to evaluate to get the result (prioritising from left to right). So anvil.users.get_user() never gets run.

2 Likes

Thanks, Shaun, that was a brain-dead moment for me.

1 Like