Link news articles to users
We’re going to change the list of news articles displayed on the Homepage, depending on who is logged into our app.
Step 2: Adding users to articles
Next, we want to store the logged in user in this ‘user’ column, whenever we add a news article to the database.
To get the currently logged-in user, we can call
anvil.users.get_user(). This returns the currently logged-in user, or
None if no user is logged in.
Click on ‘ServerModule1’ in the App Browser.
Let’s modify the
add_article function to store the currently logged-in user in our ‘articles’ Data Table. Update your
add_article function to look like this:
@anvil.server.callable def add_article(article_dict): # Get the logged in user current_user = anvil.users.get_user() # Check that someone is logged in if current_user is not None: app_tables.articles.add_row( created=datetime.now(), # Store the logged in user in the 'user' column user=current_user, **article_dict )
Run your app again, log in and add a new article. Then stop your app, and go back to your Data Tables. You’ll see your new article row now contains a link to a record in the ‘Users’ table.
Nice work – we’re now linking new articles to the user that’s logged in! Time for Chapter 3.
Nice work – we’re now linking new articles to the user that’s logged in! In Chapter 3, we’ll add user permissions.