Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

htmx and django: return HX-Trigger header with json data show error `SyntaxError: JSON.parse…`

I’m following the examples in https://htmx.org/headers/hx-trigger/

my view

def my_view(request):
    res = render(request, 'index.html')
    res.headers["HX-Trigger"] = ...
    return res

this code works

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

res.headers["HX-Trigger"] = "showMessage"

while below code will cause error SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data

res.headers["HX-Trigger"] = {"showMessage": "Here Is A Message"}

What should I do?

>Solution :

You need to pass a valid JSON string as the header – not a dictionary, because a dictionary will not be converted to JSON automatically (which is why the client fails to parse it).

The following will work:

res.headers["HX-Trigger"] = '{"showMessage": "Here Is A Message"}'   # Note, this is a string

or, if you don’t want to generate the JSON string manually:

import json

res.headers["HX-Trigger"] = json.dumps({"showMessage": "Here Is A Message"})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading