We’ll use a Server Module to update an existing article in the Data Table.

We’re using a Server Module because code in Server Modules can be trusted, and we might want to add authentication or other logic to this update code. We recommend doing it this way for all database-backed apps.

Add this function to your Server Module:

@anvil.server.callable
def update_article(article, article_dict):
  # check that the article given is really a row in the ‘articles’ table
  if app_tables.articles.has_row(article):
    article_dict['updated'] = datetime.now()
    article.update(**article_dict)
  else:
    raise Exception("Article does not exist")

This function takes two arguments: the existing article, and the updated article.

We’ve added a security check, to first check that the article we were given is really a row in the ‘articles’ table. If we didn’t make this check, a malicious user could edit any row in any data table by passing it to this function!

This check must occur in a Server Module because server code can be trusted.

Need to validate your inputs in more detail – for example, to ensure that every article has a name? Check out our recommendations for validating inputs in CRUD apps.

Finally, we’ll call update_article from the client when we want to update a news article. Our ‘Save’ and ‘Cancel’ buttons return the values ‘True’ and ‘False’, respectively, when clicked. If we wrap our alert in an if statement, the code block will be executed if the user clicks ‘Save’.

Change your edit_article_button_click function to the following:

  def edit_article_button_click(self, **event_args):
    # Create a copy of the existing article from the Data Table 
    article_copy = dict(self.item)
    # Open an alert displaying the 'ArticleEdit' Form
    # set the `self.item` property of the ArticleEdit Form to a copy of the article to be updated
    save_clicked = alert(
      content=ArticleEdit(item=article_copy),
      title="Update Article",
      large=True,
      buttons=[("Save", True), ("Cancel", False)]
    )
    # Update the article if the user clicks save
    if save_clicked:
      anvil.server.call('update_article', self.item, article_copy)