Search code examples
pythonhtmlflaskjinja2htmx

HTMX post is returning b''?


I have a post request that is supposed to be recieved by an app route. But when it's recieved by the app route it's only returning b''. Which is, if I'm not mistaken, the same as empty json.

I'm using htmx.logAll(); in my javascript file to log the htmx. In the logs I can see that hx-vals looks like this: hx-vals="{'station_id': '158820'}". Which is not what is recieved by my flask app. In the flask route I use print(request.data) to print the returned json, which results in b''

What am I doing wrong?

Html, htmx and jinja2:

<input
  hx-post="/toggle_favourite"
  hx-trigger="click"
  hx-target="this"
  hx-swap="none"
  hx-vals="{'station_id': '{{ item[0] }}'}"
</input>

The json is used using this code in my app route: station_id = request.json.get('station_id') but the flask app returns 400.


Solution

  • htmx is not handling json requests by default.

    You either need to use request.form to read the data on the backend side or use htmx extention to handle json format.

    Ref: https://htmx.org/extensions/json-enc/