Episode 9 of 13

Submitting the Form with HTMX

Learn about Submitting the Form with HTMX

HTMX Form Submission

Instead of a traditional form submission that causes a full page reload, we will use HTMX to submit the form asynchronously. Add the hx-post attribute to the form element, pointing to the create_contact URL. Set hx-target to specify where the server's response should be placed, and hx-swap to define how the content should be replaced.

Handling the POST Request

Update the create_contact view to detect whether the request is an HTMX request. The django-htmx middleware adds a request.htmx attribute that you can check. If the form is valid and the request is from HTMX, return a partial template response instead of a redirect. If the form is invalid, return the form with errors so HTMX can display them inside the modal.

Including CSRF Tokens

Django requires a CSRF token for all POST requests. When using HTMX, you need to include the token in the request headers. Add hx-headers with the CSRF token value from the cookie, or include a hidden input with the csrf_token template tag inside the form element. Both approaches satisfy Django's security requirements.

Refreshing the Contact List

After a successful form submission, the contact list needs to be updated to show the newly created contact. Use the HX-Trigger response header in your Django view to emit a custom event like "contactListChanged". On the contact list element, add hx-trigger="contactListChanged from:body" with hx-get pointing to the contact list URL. This causes the list to automatically refresh when a new contact is saved.

Closing the Modal on Success

When the form submission succeeds, return a response that either empties the modal container or includes JavaScript to close the dialog element. The user sees the modal disappear and the contact list update simultaneously, creating a smooth and responsive experience.

Encoding for File Uploads

Since our form includes an image upload field, the form element must use enctype="multipart/form-data". Add the hx-encoding="multipart/form-data" attribute to tell HTMX to send the file data in the correct format. Without this, uploaded files will not be included in the request.