Link news articles to users
Let’s now modify our app to only display news articles on the Homepage if they were added by the currently logged-in user.
Step 1: Link the data tables
We want to show each user only the articles they added. To do this, we’ll create a link between our Articles and Users Data Tables. Each time a user adds a new article, we’ll store their user information in the Articles Data Table.
To link the tables together, open the Articles Data Table and click the ‘+’ to add a new column. Choose ‘Link to table…’, ‘Users’, and select ‘Single Row’. Call the newly created column ‘user’.
Step 2: Add 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 sidebar of the Anvil Editor.
Let’s modify the
add_article function to store the currently logged-in user in our Articles Data Table. Update the
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.