Welcome | Get started | Dive | Contribute | Topics | Reference | Changes | More

Introduction to actions

Defining custom actions

Application developers can define new custom actions by

  • applying the action() decorator to a method of a database model or an actor, or by

  • subclassing the Action class and instantiating them as an attribute of the model or database model or actor.

The action() decorator

You can use the action() decorator to to define custom actions.

Any arguments you pass to the decorator are forwarded to Action.__init__(). In practice you’ll possibly use: label, help_text and required_roles.

The vote action

The Polls tutorial has a usage example of the first approach:

@dd.action(help_text="Click here to vote this.")
def vote(self, ar):
    def yes(ar):
        self.votes += 1
        self.save()
        return ar.success(
            f"Thank you for voting {self}", "Voted!", refresh=True)
    if self.votes > 0:
        msg = f"{self} has already {self.votes} votes!"
        msg += "\nDo you still want to vote for it?"
        return ar.confirm(yes, msg)
    return yes(ar)

Above code defines a method on the Choice class, and that method is decorated. The @dd.action decorator converts its method into an action instance. It accepts keyword parameters to specify additional attributes for the action, for example its label, its help_text, icon_name or button_text.

The action method itself must have the following signature:

def vote(self, ar):
    ...
    return ar.success("It worked")

Where ar is an ActionRequest (it holds information about the incoming web request that called the action).

  • callback and confirm lets you define a dialog with the user using callbacks.

  • success and error are possible return values where you can ask the client to do certain things.

See also

See also More about actions and Everything about actions.