Django forms with htmx increase the number of requests


When using htmx to create an ux similiar to SPA with django forms you need to bind the keyup event on every input(almost all) to offer that on type validation and disable the submit button.

The problem is that on every keystroke you’ll have a request, increasing the number of requests per user. I didn’t measure to see if that’s a problem, but anyone noticed that?

There is a way to put a script tag with some js validation without duplicating the forms rules?

There is a way to the form itself create a json(i don’t know) or script tag on the generated form html with js validation to prevent duplication?

You can’t have it both ways.

Since you must always validate data being submitted, you are always going to have the form code on the server. If you wish to also pre-screen data entry in the browser, then you would need to have JavaScript running in the browser.

If you want to do that type of browser-based test, you can do it in JavaScript, or you could use HTMX to do it (check out validation and scripting for some ideas)

If you really only want the validation running in the server and you want to avoid the overhead of HTTP requests, you could set up something using a websocket and Channels to perform on-the-fly field validation.

hx-trigger supports a number of event modifiers, that can be used to control when the event is dispatched. Likely the delay or throttle modifiers would address your case here.

That makes sense when we’re talking about a search input where you don’t need to validate the field.

When we’re talking about an email field / money field with max and min or anything that requires some sort of validation when you type, you need to validate on each keystroke

You can still denounce. It’s not clear you need to validate every keystroke.

But yes, in the limit you’re increasing requests. If that’s an issue you may need to do something else. (But I’d imagine you’d get a lot further than you’d think before it really becomes a worry.)

Thanks a lot for your suggestion, i’ll test it.

I’m not against client side validation, but i wanna find the solution without losing the SPA-like ux in forms validation without duplicating the forms rules…

yeah, i believe you’re right … Donald Knuth feelings here…

1 Like