Messages
hx-requests
has an asyncronous messaging framework, hx-messages
. It’s very convenient for notifiying the user when the form is valid/ invalid.
Note
hx_message
framework is based on Django’s messages framework
Setup
To use hx-messages
a few things need to be set…
In
settings.py
setHX_REQUESTS_USE_HX_MESSAGES
: bool that defines whether or nothx-messages
should be used (default is False)In
settings.py
setHX_REQUESTS_HX_MESSAGES_TEMPLATE
: path to a template to be used for the messages. The context in the template has access tomessages
.
example-message-template.html
<div id="hx_messages" hx-swap-oob='true'>
<ul class="messages">
{% for message in messages %}
<li class="alert {{ message.tags }}">{{ message|safe }}</li>
{% endfor %}
</ul>
</div>
An empty div (or any Html element) with the same id as the one in the messages template needs to be put in your base Html file. (
hx-messages
leverages Htmx’shx-swap-oob
)
<div id="hx_messages" hx-swap-oob='true'></div>
In
settings.py
setHX_REQUESTS_USE_DJANGO_MESSAGE_TAGS
: bool that defines whether or nothx_messages
should use Django’s message tags. If set to True then there is no need to setHX_REQUESTS_HX_MESSAGE_TAGS
(default is False)If
HX_REQUESTS_USE_DJANGO_MESSAGE_TAGS
is False, insettings.py
setHX_REQUESTS_HX_MESSAGE_TAGS
: dict just like Django’s message tags
from hx_requests.hx_messages import HXMessageTags
HX_REQUESTS_HX_MESSAGE_TAGS = {
HXMessageTags.DEBUG: "alert-info",
HXMessageTags.INFO: "alert-info",
HXMessageTags.SUCCESS: "alert-success",
HXMessageTags.WARNING: "alert-warning",
HXMessageTags.ERROR: "alert-danger",
}
Setting a Message
You can set a message anywhere within an HXRequest
by doing the following:
def form_valid(self, **kwargs) -> str:
self.form.save()
# Set a message
self.messages.success("Form was successfully saved!")
return ...
- Notes:
Sucess is the level of the message and is used to retrive the tag from
HX_REQUESTS_HX_MESSAGE_TAGS
can also set
self.messages.error()
,self.messages.warning()
,self.messages.info()
andself.messages.debug()
Disabling Messages
If HX_REQUESTS_USE_HX_MESSAGES
is set to True, there are some default messages set in some of the HXRequests
.
To disable messages on any HXRequest
set show_messages
to False
class MyHXRequest(BaseHXRequest):
...
show_messages = False
Tip
Tip
Toasts are a good template to use for hx_messages
. Because the messages are asyncronous and the page doesn’t reload, a user may not see a message banner that is set on the top of the page, but a toast that is fixed to the top right cornder of the page will always be visible.