Actions
PyBlade Live actions are methods on your component that can be triggered by frontend interactions like clicking a button or submitting a form.
They provide the developer experience of being able to call a Python method directly from the browser, allowing you to focus on the logic of your application without getting bogged down writing boilerplate code connecting your application's frontend and backend.
Let's explore a basic example of calling a save action on a CreatePost component:
from pyblade import LiveComponent
from app.models import Post
class CreatePost(LiveComponent):
title = ""
content = ""
def save(self):
Post.objects.create(title=self.title, content=self.content)
def render(self):
return self.render_template('live.create-post')<form pb:submit="save"> // [!code highlight]
<input type="text" pb:model="title">
<textarea pb:model="content"></textarea>
<button type="submit">Save</button>
</form>In the above example, when a user submits the form by clicking "Save", pb:submit intercepts the submit event and calls the save() method on the server.
In essence, actions are a way to easily map user interactions to server-side functionality without the hassle of submitting and handling AJAX requests manually.
Confirming an action
When allowing users to perform dangerous actions — such as deleting a post from the database — you may want to show them a confirmation alert to verify that they wish to perform that action.
PyBlade Live makes this easy by providing a simple directive called pb:confirm:
<button
type="button"
pb:click="delete"
pb:confirm="Are you sure you want to delete this post?"
>
Delete post
</button>When pb:confirm is added to an element containing a PyBlade Live action, when a user tries to trigger that action, they will be presented with a confirmation dialog containing the provided message. They can either press "Yes" to confirm the action, or press "Cancel" or hit the escape key to cancel the action.
Passing parameters
PyBlade Live allows you to pass parameters from your PyBlade template to the actions in your component, giving you the opportunity to provide an action additional data or state from the frontend when the action is called.
For example, let's imagine you have a TodoList component that allows users to delete a task. You can pass the task's ID as a parameter to the delete() action in your PyBlade Live component. Then, the action can fetch the relevant task and delete it from the database:
from pyblade import LiveComponent
from app.models import Task
class TodoList(LiveComponent):
def mount(self):
self.tasks = Task.objects.all()
def delete(self, id: int):
task = Task.objects.get(id=id)
task.delete()
def render(self):
return self.render_template("live.todo-list")
<div>
@for (task in tasks)
<div key="{{ task.id }}">
<h1>{{ task.title }}</h1>
<span>{{ task.content }}</span>
<button pb:click="delete({{ task.id }})">Delete</button> // [!code highlight]
</div>
@endfor
</div>For a task with an ID of 2, the "Delete" button in the PyBlade template above will render in the browser as:
<button pb:click="delete(2)">Delete</button>When this button is clicked, the delete() method will be called and id will be passed in with a value of "2".
Don't trust action parameters !
Action parameters should be treated just like HTTP request input, meaning action parameter values should not be trusted. You should always authorize ownership of an entity before updating it in the database.
For more information, consult our documentation regarding security concerns.
Skipping re-renders
Everytime an action in your component is trigerred, the render() method is called to re-render the component.
But, sometimes there might be an action in your component with no side effects that would change the rendered PyBlade template when the action is invoked. If so, you can skip the render portion of PyBlade Live's lifecycle by adding the @renderless decorator above the action method.
Let's say you want to track when a user clicks on a button, but this interaction doesn’t change any visible part of the UI.
from pyblade import LiveComponent
from pyblade.decorators import renderless
from app.models import ActivityLog
class ActivityTracker(LiveComponent):
user_id = None
def mount(self, user_id):
self.user_id = user_id
@renderless
def track_click(self):
# Log the click to your database or analytics service
ActivityLog.objects.create(user_id=self.user_id, action="clicked_button")<button pb:click="track_click" class="btn">
Click Me
</button>What happens here is that when the track_click method is called, the @renderless decorator tells PyBlade Live not to call the render() method afterward.
This saves time and prevents an unnecessary re-render of the component. It’s perfect for fire-and-forget logic — like logging, silent actions, or external calls.
If you prefer to not utilize method attributes or need to conditionally skip rendering, you may invoke the skip_render() method in your component action:
class PostDetail(LiveComponent):
...
def increment_view_count():
self.post.increment_views()
self.skip_render()
def render():
return self.render_template('live.show-post');
Calling actions from JavaScript
In a component's @script, $pb calls its actions like JavaScript functions, with the arguments they take:
$pb.increment();
$pb.save(post_id, { notify: true });
$pb.$call('save', post_id); // the same, with the action's name as a stringAny name that is not a property of the component is taken as an action. Only methods the component declares can be called, exactly as from pb:click.
Every call returns a promise, settled once the server has answered and the component has been updated:
await $pb.save();
$pb.$el.classList.add('saved');Updating the page before the server answers
Calling an action from JavaScript lets you show its result right away, and let the server catch up. Here, the bookmark icon is filled as soon as the button is clicked, while the bookmark is saved in the background:
from pyblade import LiveComponent
class PostDetail(LiveComponent):
bookmarked: bool = False
def mount(self, post):
self.post_id = post.id
self.bookmarked = post.is_bookmarked_by(self.request.user)
def bookmark_post(self):
post = Post.objects.get(id=self.post_id)
post.bookmark(self.request.user)
self.bookmarked = post.is_bookmarked_by(self.request.user)<div>
<button class="bookmark">
<svg class="outlined" pb:show="!bookmarked">...</svg>
<svg class="solid" pb:show="bookmarked">...</svg>
</button>
</div>
@script
<script>
$pb.$el.querySelector('.bookmark').addEventListener('click', async () => {
// Show the result at once...
$pb.$el.querySelector('.outlined').style.display = 'none';
$pb.$el.querySelector('.solid').style.display = '';
// ...and let the server save it. Its answer brings the page up to date.
await $pb.bookmark_post();
});
</script>
@endscriptWhen the user clicks the button:
- The filled icon is shown at once, without waiting for the network.
bookmark_post()is called on the server and saves the bookmark.- The server's answer renders the component again, with
bookmarkedas the database says.
Magic actions
PyBlade Live provides a set of "magic" actions that allow you to perform common tasks in your components without defining custom methods. These magic actions can be used within event listeners defined in your PyBlade templates.
Refreshing a component
Sometimes you may want to trigger a simple "refresh" of your component. For example, if you have a component checking the status of something in the database, you may want to show a button to your users allowing them to refresh the displayed results.
You can do this using PyBlade Live's simple refresh action anywhere you would normally reference your own component method:
<button type="button" pb:click="refresh">...</button>When the refresh action is triggered, PyBlade Live will make a server-roundtrip and re-render your component without calling any methods.
It's important to note that any pending data updates in your component (for example pb:model bindings) will be applied on the server when the component is refreshed.
Calling parent actions
The parent magic variable allows you to access parent component properties and call parent component actions from a child component:
<button pb:click="parent.remove_post({{ post.id }})">Remove</button>In the above example, if a parent component has a remove_post() action, a child can call it directly from its PyBlade template using parent.remove_post().
Updating properties
The set magic action allows you to update a property in your PyBlade Live component directly from the PyBlade template. To use set, provide the property you want to update and the new value as arguments:
<button pb:click="set('query', '')">Reset Search</button>In this example, when the button is clicked, a network request is dispatched that sets the query property in the component to an empty string ''.
Toggling Boolean values
The toggle action is used to toggle the value of a boolean property in your PyBlade Live component:
<button pb:click="toggle('sort_asc')">
Sort {{ "Descending" if sort_asc else "Ascending" }}
</button>In this example, when the button is clicked, the sort_asc property in the component will toggle between True and False.
Dispatching events
The emit action allows you to dispatch a PyBlade Live event directly in the browser. Below is an example of a button that, when clicked, will emit the post-deleted event:
<button type="submit" pb:click="emit('post-deleted')">Delete Post</button>Pro tip
You can also use the dispatch action to dispatch events. It works the same way as emit.
Accessing event objects
The event action may be used within event listeners like pb:click. This action gives you access to the actual JavaScript event that was triggered, allowing you to reference the triggering element and other relevant information:
<input type="text" pb:keydown.enter="search(event.target.value)">When the enter key is pressed while a user is typing in the input above, the contents of the input will be passed as a parameter to the search() action.
Event listeners
PyBlade Live supports a variety of event listeners, allowing you to respond to various types of user interactions:
| Listener | Description |
|---|---|
pb:click | Triggered when an element is clicked |
pb:submit | Triggered when a form is submitted |
pb:change | Triggered when an input value changes |
pb:keydown | Triggered when a key is pressed down |
pb:keyup | Triggered when a key is released |
pb:mouseenter | Triggered when the mouse enters an element |
pb-* | Whatever text follows pb- will be used as the event name of the listener |
Because the event name after pb- can be anything, PyBlade Live supports any browser event you might need to listen for. For example, to listen for transitionend, you can use pb:transitionend.
Listening for specific keys
You can use one of PyBlade Live's convenient aliases to narrow down key press event listeners to a specific key or combination of keys.
For example, to perform a search when a user hits Enter after typing into a search box, you can use pb:keydown.enter:
<input pb:model="query" pb:keydown.enter="searchPosts">You can chain more key aliases after the first to listen for combinations of keys. For example, if you would like to listen for the Enter key only while the Shift key is pressed, you may write the following:
<input pb:keydown.shift.enter="...">Below is a list of all the available key modifiers:
| Modifier | Key |
|---|---|
.shift | Shift |
.enter | Enter |
.space | Space |
.ctrl | Ctrl |
.cmd | Cmd |
.meta | Cmd on Mac, Windows key on Windows |
.alt | Alt |
.up | Up arrow |
.down | Down arrow |
.left | Left arrow |
.right | Right arrow |
.esc | Escape |
.tab | Tab |
.caps-lock | Caps Lock |
.equal | Equal, = |
.period | Period, . |
.slash | Forward Slash, / |
Event handler modifiers
PyBlade Live also includes helpful modifiers to make common event-handling tasks trivial.
For example, if you need to call event.preventDefault() from inside an event listener, you can suffix the event name with .prevent:
<input pb:keydown.prevent="...">Here is a full list of all the available event listener modifiers and their functions:
| Modifier | Key |
|---|---|
.prevent | Equivalent of calling .preventDefault() |
.stop | Equivalent of calling .stopPropagation() |
.window | Listens for event on the window object |
.outside | Only listens for clicks "outside" the element |
.document | Listens for events on the document object |
.once | Ensures the listener is only called once |
.debounce | Debounce the handler by 250ms as a default |
.debounce.100ms | Debounce the handler for a specific amount of time |
.throttle | Throttle the handler to being called every 250ms at minimum |
.throttle.100ms | Throttle the handler at a custom duration |
.self | Only call listener if event originated on this element, not children |
.camel | Converts event name to camel case (pb:custom-event -> "customEvent") |
.dot | Converts event name to dot notation (pb:custom-event -> "custom.event") |
.passive | pb:touchstart.passive won't block scroll performance |
.capture | Listen for event in the "capturing" phase |
Disabling inputs while a form is being submitted
Consider the CreatePost example we previously discussed:
<form pb:submit="save">
<input pb:model="title">
<textarea pb:model="content"></textarea>
<button type="submit">Save</button>
</form>When a user clicks "Save", a network request is sent to the server to call the save() action on the PyBlade Live component.
But, let's imagine that a user is filling out this form on a slow internet connection. The user clicks "Save" and nothing happens initially because the network request takes longer than usual. They might wonder if the submission failed and attempt to click the "Save" button again while the first request is still being handled.
In this case, there would be two requests for the same action being processed at the same time.
To prevent this scenario, PyBlade Live automatically disables the submit button and all form inputs inside the <form> element while a pb:submit action is being processed. This ensures that a form isn't accidentally submitted twice.
To further lessen the confusion for users on slower connections, it is often helpful to show some loading indicator such as a subtle background color change or SVG animation.
PyBlade Live provides a pb:loading directive that makes it trivial to show and hide loading indicators anywhere on a page. Here's a short example of using pb:loading to show a loading message below the "Save" button:
<form pb:submit="save">
<textarea pb:model="content"></textarea>
<button type="submit">Save</button>
<span pb:loading>Saving...</span> // [!code highlight]
</form>Security concerns
Remember that any method in your PyBlade Live component can be called from the client-side, even without an associated pb:click handler that invokes it. In these scenarios, users can still trigger the action from the browser's DevTools. So to make your application secure, read our security concerns before using actions.