What Are FormHxRequests?

The FormHxRequest is modeled after Django’s FormView, CreateView and UpdateView. If the package was being rewritten it could be there would be three separate classes, but for now they are all combined into one. Which on one hand makes it easier to use, but on the other hand can make it a little more coupled.

It simplifies working with forms in Django and HTMX by providing built-in methods, attributes , and behaviors that streamline form handling.

The FormHxRequest uses a form_class attribute to set which form to use. This could be a regular form or a model form. On GET the form is accessible in the context as form and the template defined in GET_template has access to it. On POST the form is validated and if it is valid the form_valid method is called, if it is invalid the form_invalid method is called just like in Django’s FormView.

If the form is a model form and hx_object (object is the parameter in the tags) is passed in to the template tags on GET/ POST then the FormHxRequest is treated like a UpdateView and the object is passed in to the form as an instance. If the form is a model form and the object is not passed in then the FormHxRequest is treated like a CreateView and an instance is created from the form.

On POST the form_valid method is called if the form is valid and the form_invalid method is called if the form is invalid.

form_valid by default calls the save method of the form and sets a success message. If you want to do something else you can override the form_valid method, ie like sending an email.

form_invalid by default sets a message and returns the form with the errors and it does this by changing the template rendered back to the GET_template so that the form will be still visible but now with the errors.

Other built in behavior includes support for setting form_kwargs (even the ability to automatically set from the template tag),

hx_object

The hx_object is the object passed into the template tag and as mentioned above is used as the instance for the form if the form is a model form. It is accessible in the templates (GET_template and POST_template) as hx_object by default, but can be renamed by setting hx_object_name in the FormHxRequest class.

This can be a little confusing, for example:

you have a page that has the object passed in fomr the view’s context as user

<button {% hx_get 'my_form_request' object=user %}></button>

But in the GET_template you need to access the object as hx_object because that is the default

<p>{{ hx_object.username }}</p>
<p>{{ hx_object.email }}</p>

<form>
    {{ form.as_p }}
    <but {% hx_post 'my_form_request' object=hx_object %}>Submit</button>
</form>

Tip

Most of the time you will want the hx_object_name to match the context of the view so that when the GET_template is the same as the view’s template you can just use the same context variable name.