# Modern apps with Django, HTMX, Tailwind CSS and Alpine.js with Andrej Baranovskij

Source: https://djangotv.com/videos/djangocon-us/2022/modern-apps-with-django-htmx-tailwind-css-and-alpinejs-with-andrej-baranovskij-dcus-2022/
Date: 2022-11-24
Speakers: Andrej Baranovskij

## Summary

Andrej Baranovskij shows how to build a responsive employee-management interface with Django, HTMX, Alpine.js, Tailwind CSS, Flowbite, and django-widget-tweaks. Django models and model forms provide fields, relationships, constraints, widgets, and validation, while HTMX sends partial GET and POST requests so only the form or table is replaced instead of reloading the page. Alpine.js controls local state such as showing the edit form and disabling other edit buttons, and HTMX events refresh the table after a successful save. The example also demonstrates field-level and custom validation errors, success messages, and salary-range and uniqueness checks.

## Transcript

### [00:00] Modern Django Application Overview

[00:21] Hello, my name is Andrey Barnowski and I'm very happy to present my session on this Django conference. The session will be about how to build modern web applications with Django. Using alpinejs htmx and tailwind my background I'm working quite a lot with Python machine learning and in the past I was spent many years working with Java Enterprise. Building web enterprise applications but for the past few years I busy with machine learning and implementing different enterprise

[01:06] use cases in machine learning field and to build UI for machine learning I'm using Django because I found it quite good in because you can quite easily define the model and models, model forms, views and then you render UI data like a table structures forms out of out of this definitions that you created in the jack Django backend and This helps to create clean UIs and it helps

[01:52] to inform to enforce correct data to when user is saving data and so on. And I decided to look into HTMX because HTMX helps to Execute partial requests with Django without reloading the whole page when user submits data, but you execute just a partial request with HTMix. Yeah, so let's first of all probably first thing first, let's look into the application that I'll be talking today about, and this application implements table And this edit button for each row, so we can click for example edit

[02:37] for the first record and we get edit for editable form below the table. Right and What you can do here you can change any value for example 2 press save and you see that data is saved successfully And it's instantly updated on a table above, right? So as expected. And as soon as you edit any record you can see all the other buttons disabled so you can edit records just one record at a time you press close edit functionalities enabled you can let's open The last record for Steven, and if we try to

[03:22] for example, I'll try to put some email which is not unique, for example Let's use this value and try to save it and to get back validation error from Django because these unique constraint in Django model which checks that email field value must be unique for all the users so there is validation as well Okay, so the this is the application and my idea was to have something simple use case but the same practical with way you would be able to update data and we could see how validation works, how we can return validation errors back. Then we have multiple regions on this page

### [04:08] Templates and Frontend Libraries

[04:08] like table and also edit form And when we successfully edit data in form we update another region and for that we're using HTMX events which is returned back with on successful save and then HTMX library is able to get fresh data for the for the table and so on. So these there are quite of those interactivity use cases here which probably you w would be useful for your own applications in terms of practicality. Alright, so if you switch to the application, so let's see what kind of template HTML templates we have here. So here's the base template and in the base template we import

[04:55] tailbind CSS And by the way, we're using FlowBite library to implement all the UI for the table, for the fields and for so on, for other elements like buttons for example. FlowByth is open source library. It comes also with JavaScript support to implement interactivity, but we are not using any complex components from FlowBite here. So it's enough just to include the tailwind and that's all then flow by styling would work. We're using Alpine GS to implement interactivity, like to disable the button or hide the edit form and so on so for that we include alpinejs and htmx is the main library which helps to implement a partial request

[05:42] get back response and display this response in the parts of the page so we include HTMX for that. Okay, then we Have index page which extends from base and have we include some static div with text just to demonstrate that when we are running HTMX requests we are not reloading entire page portions of the page they stay without any reload We include employees HTMX here inside the index and employees HTMX comes with two blocks. First block is table, second one is the form And we can we are using Alpine GS attributes directly on divs.

[06:28] With x show attribute we refer to the show edit form variable by default it's false. This means this div is hidden and when we are clicking edit inside the table then this variable is set to true and then div becomes visible. We hit cancel button inside edit form, then we set value false to the show edit form variable and this variable becomes it gets value false and the block edit block becomes hidden so we can we can check that and for that let's open View table and edit form. So in the view table, this is the

[07:14] edit button, and we see this Alpine. js on click event listener it and says show edit form equal true this means when we hit the button then show edit form becomes true and edit block is visible and we are also using disabled We are overriding disabled property for the button also using Alpine GS and This means that when variable is true, then all edit buttons are disabled. And later, when in edit form we'll set this variable to false, then buttons will be enabled and user could hit edit form for another record to edit the data

### [08:00] Django Models and Relationships

[08:00] so this is over here we can go to the to the bottom this is a closed button and or cancel button and we set show edit form equal false. This means the form becomes hidden and edit buttons become editable. Okay, so that's about the structure of the UI templates and now let's look into the how the models are defined for that application. So the main model is employees model. So table and edit form are rendered out of this model. There is a set of fields defined for the model, like a last name, email, higher date, and so on.

[08:47] All the fields are assigned with attributes like a max length, primary key max digits decimal places and so on right so Also we have ordering is being specified for this model and there are a couple of constraints like check constraint. It checks if salary it's it's enforcing the rule that salary must be positive and there's a unique constraint it checks that the email value must be unique for all the records for all the employees. There are a couple of foreign keys defined, one for manager ID, second for department ID, and also there is a foreign

[09:32] key. for job ID for manager ID foreign key it points to itself to employees model because managers are all also the same employees right And there are two other classes defined, one for department model and another one for job model. So those models are used to implement foreign key relationship for departments and for jobs. Right, so this is the model definition, and as soon as you define the models in Django application, then you need to run Django migrate utility. and construct a local database structure

### [10:17] Model Forms and Validation

[10:17] which would correspond to the model class as you defined to all the fields constraints and attributes. And then out of the box you could fetch data from that database and you could push data as soon as data is updated and so on. Right, so we've got models. Next we also discussed models, we discussed check constraints, and now let's look into the forms. So, since we have a model, we can define Django model form on top of the model and we can specify in the model form which fields we want to display on UI.

[11:02] And also we dispate some sort of widget configuration here for the higher date. We specify that higher date field is a date input field. And later on UI when form will be rendered then like a calendar component will be automatically attached to the higher date fields which is created comes out of the box. Alright, and another huge advantage of model forms that you can do validation right away right here in inside the model form. And you write a method called clean, then field name. So clean email, clean salary and so on. So when you

[11:47] hit save And all those methods will be executed automatically for you. You need you don't need to call anything by yourself. All the methods will be executed and you can enforce rules inside those methods. If some of the rules will fall will fail, then the transaction will stop. And validation text will be reported back to the caller and it will be propagated to the UI and reported back to the user. So in clean email, for example, we check that for the email format. In clean salary, it's a bit more interesting here what we have over here we get current job ID.

[12:33] for the current employee that we are trying to update data and we get salary value and later we could we get through the foreign key relationship we get minimum and maximum salary for this employee that we are current currently working with and we can check if the salary that we are trying to save if the salary is in range between minimum and maximum as it is defined in the foreign key relationship If the new value doesn't fall into this interval then we report back the validation error. So this is how it works. Okay, this is model form.

### [13:18] URLs and Django Views

[13:18] Next let's take a look into the views Or URL URLs. So under URLs we have one root URL which points to the index Then there are two URLs that work with employees data. First one it returns list of employees and the second one is responsible to handle post request. when we actually when we actually executing post requests and sending submitting data to update a specific employee Also, it can work to get employee because if when we pass primary key to this request, we could get sp information about specific employee and

[14:04] render data for of that employee inform. And I'm using Django Browser Reload plugin to be able to refresh application automatically when f when you when you when you do any change in quality when you click save then The application is reloaded in Google Chrome automatically. In Safari, I think it doesn't work this way, but in Google Chrome it works. It helps to save lots of time and improve developer experience. Okay, now let's look into the views. Views. Let's look into the views

[14:51] And let's see how they are implemented. So first this index view. It returns index. html as a main page of this application. And in the get methods of this class we are fetching all the employees and list of employees included into the context and return back with Django render function and we're also returning the template name. So what this means if you go back to the employees HTMX this means we'll we are bringing the content for this first view which renders the table view table this one

[15:36] And over here we got the loop for employee in employees. We are basically drawing the records for employees data. So This employees variable is coming through the context that is defined here in the view. Right, and yeah, another thing is So that's for the main page and later we are using employee table view if you look into the URLs. Yeah, we're using it also to bring back the list of employees through this one and is being used when we are doing refresh

[16:21] when event is received from the edit form and we want to refresh the table then we are using this view and it's basically similar thing the only difference is that We are not returning the whole index page. We are returning only view table HTMX template which contains only the table. And because when something changed inside the edit form, then we don't need to reload the whole page we just want to redraw the table and we're returning the template with the table only and also all employees all the data for the table

[17:08] And the third view is edit view. So in this case we're returning the edit form And over here in the get methods we are getting by the primary key we are getting entry for the employee to be displayed in an edit form and we're constructing employee model form with the instance of employee including this form into the context and returning back with the template. And this is how edit form is displayed. And this post method for this view because we're handling a data update in this view. So what happens here

[17:53] actually what we do here is we get information about the employee data that we're updating right now We are construct constructing the instance of the form and we are validating the form. And if and this will trigger all those validations defined in a model form, also in the model, all the constraints and so on. If everything is fine, then if there are no validation errors, we are hitting save. Data is saved and then we're turning success, returning the same form back and Also we're in response we are including HTMX trigger employ with name employee changed and when this

[18:39] When this event employee change would be received and detected by HTMX then we'll have subscriber logic which will trigger refresh for the table and this refresh for table would execute employee table view and fetch fresh data for to be displayed in table. In case of the error then when Not doing anything like that. We are then just collecting list of errors and we're returning the same template, the same template which is added from HTMX. And we are attaching to this template list of errors that will be displayed on UI.

### [19:25] HTMX Edit Requests

[19:25] Now we will see how to implement HTMX get. So when we are hitting edit button, this one. So we click edit, right? And we get back edit form visible. Visibility is controlled by Alpine GS and we are fetching employee data through HTMX get request So we are not copying data from the table, we are executing separate requests. And this could be valid for multiple reasons. One of them is that maybe not all data would be present

[20:13] in an HTML table roll and maybe you would want to fetch additional fields for the edit form so you would like to execute a separate request Then if you look into this button definition, yeah, so this is Alpine GS stuff over here. And then we get we define attributes on top of html button that are specific to htmx library so first one get then there's a target and swap So in GET we execute Django expression language using URL expression

[20:58] and we are referring to the edit employee. URL entry which is defined in URLs file, URL script and we Passing as URL parameter employee ID. So from the current records that we are working right now where user is pressing edit we are getting employee ID from employee object because all the roles are displayed in a loop and employee refers to the current role. And as a target for this HTMX

[21:44] get event, we are specifying edit form. So this is over here. If you go Scroll up. This is the edit form is defined so this is form which renders edits editable data. And we're using swap attribute outer HTML. This means when response will come back. For the target edit form, we would like to replace it with whatever HTML response would come from the back end. We would redraw it. basically and let's look into the what is the edit employee so edit employee is defined over here This one and it's a Django

[22:29] puff that points to the edit employee. We pass primary key and we are referring view class employee edit view So if we open it again, so employee edit view is over here and we'll execute get request. We get primary key from the URL parameter and we'll get we get employee model, then we initialize instance of employee form and we pass it back with the through the context. and we are passing data the form context and we are passing template name edit form htmx this one and all of this is sent back

[23:14] as a jango for the Django render function and HTMX is taking care or for this definition. It says that it will replace target with id edit form So whatever response is coming back, it will be included into this target. Right, and It's important to mention that if you look into the edit form, so each of the edit elements is implemented with a render field For example, and we are referring here to the form, first name, and so on. So form is coming from the context, and this is the attribute name we're using placeholder and using class from the flow byte to

[24:01] Have a nice representation of this ui component using tailwind implemented by the flow byte, right? And to render the form fields to automatically get validation functionality and so on, we are using if you look into the Base settings and on top of that over here we're using widget twix plugin which helps to render nicer form elements for Django And if you go back to the page

[24:48] if yeah, if I think we if I try to Type something like that and see if yeah it gets invited email is expected and Yeah, if the first name or if I remove the last name, because this last name is set as required field in Django, then we get We get back the information that please fill in this field. And yeah, this is comes from those

[25:34] widget tweaks out of the box So we don't need to call this functionality. So part of the validations returned like this one when on model fields you define attributes like length or required for example then those kind of errors will be reported immediately on the field And all other validations for like constraints and validations that you define in the model form, they'll be they will be reported on safe over here. And let's see also what happens when we hit edit button. Let's see what kind of request is coming back. So if you go to the

[26:21] Developer over here and developer tools network And I hit edit button. We see that get request for employee with ID5 was executed. Okay, sorry for that. And if I move it a bit up under the Request headers, key, this bunch of stuff. sprinted and this response and let's see the actual response that is coming back.

[27:06] So this is It's a not whole response of the whole HTML page as you would expect, but this is the partial response. It's only the form is included, this edit form that we see here. And yeah, this is this response is based on HTML template as it as we have defined. And the name for this template is edit formhtmx and in views over here and in employee edit view we are returning edit form htmix over here and we're returning instance of employee forum that was constructed based on a primary key

[27:51] okay so Yeah and later it's HTMX job to include this response into the main HTML page and render it without refreshing the whole stuff Okay, we can close it and now okay. Let's open another record. Yeah, let's open maybe some different record, this one for Alexander. And now let's look into functionality of when we are actually clicking save button and what happens when we click save button. So for that we go to the edit form

### [28:39] HTMX Form Submission

[28:39] and below here we have a save button it's of type submit and this map this button is wrapped by the form And this means when we hit submit button then form will be submitted. And on top of the form tag, we using HTMX post trigger swap and include attributes. And this hidden input defined with name ID and from the form instance we are passing primary key of the current data that is displayed of ID of the current employee. And this hidden input will be used by HTMX post request to

[29:25] send it to the to the backend. So we have a post and again we're using Django expression here to reference edit employee URL And I experienced the problem with initial rendering when this edit form is hidden, then because edit employee URL pattern expects primary key, then it breaks if there is nothing no parameter passed by default when form is in a hidden state. So I'm including zero and it's working fine and later when We have a real primary key, we are sending it through this hidden variable, so as a work round in this case.

[30:11] So we have a we are using as a trigger for this execution submit and this is the subs submit event we are getting from the but from this from the button and we swap outer HTML basically because we are re redisplaying rendering the same form so the form content will be displayed with the again when response will come Yeah, and if you look into the URLs, so edit employee is the same path as we were using two

[30:58] Fetch employee data by key so in this case we are using the same path but we are posting data using the key Okay, and this is visible under employee edit view class as well because we have a we override post methods over here and what this post method does it reads hidden variable from the request id if it's not known we are getting it and assigning it to the primary key variable and getting the employee records for this primary key

[31:45] and constructing the form instance with the employee information and all the values that were updated on the UI in form they are automatically submitted with the ID with field names and Django automatically maps values with field names it maps all this data that is coming from the UI it maps with the actual model form fields. And populates the model form with the new data, and later when we execute form is valid, then it validates

[32:30] new data. And as I mentioned before, if validation is successful, then we are actually saving the data and returning back the context with along with htmx event. If there are validation errors then we are returning list of errors and display it on UI Okay, okay. Okay, so next we'll see how the table is updated when we are changing data in edit form. So like in this case Let's say that we update the salary to be 9500

### [33:16] Event-Driven Table Updates

[33:16] save and to check for Alexander the salary was updated Okay, and also if we look again into the developer tools, let's see what kind of network action happening in this case. So let's say that again we do one more update 9600 hit save So we get in this case one post request, so we are submitting the data. And in response we're getting back the form Then we get back to

[34:01] I think There are two GET requests. Yeah, so and in response we get back the table over here and over here so there are basically two identical get requests this is not ideal but yeah this is how it works and I didn't manage to find solution to run single request in this case but yeah maybe it will be improved in the future But the whole point how it works, it's it's using HTMX event. So let's look into the flow again. So what happens when we hit save button? When we hit save button we submit a form with HTMX

[34:48] post And we actually put we include the hidden element ID or here to be able to refer to the employer ID that we are updating right now. Okay, and then we look into the views. So this is the post thing and when there are no validation errors when everything is fine we hit save and do we construct the response context With the message success message which says data saved successfully. So we construct the response this way

[35:35] And additionally we include HX Tigger with the name employee change. Employee change is a custom name. And we return back this response. Right, and what happens then is because what we want to do, we want to refresh a table, right? Since we updated the data in edit form And we have on top we have a table that displays the same data and we want this table to be refreshed automatically in the same request. We don't want to hit any other button to reload the table. And we got the table inside view table HTMX over

[36:20] here and this is the table definition And we define on top of a table tag we define HTMX get. We refer to employees. And if you double check here we have employees path defined right here. Employees path. It refers to employees slash and we refer to employees table view. And if we go back to the views, then this is where we have employees table view. So employees table view is very similar to the index view. The only difference that it's using different template So probably you could

[37:06] we could use a single class and have some ch check from where this view is being initialized right now, but I thought for the simplicity and for the demonstration purpose to put those views separately. And what we have here is we get all the employees and again we include those employees into the context and return with Django render. return the context and also return view table HTMX as a template. And viewtable HTMX is actually the template that contains table itself. So we return back the table and return back the new data that will include

[37:53] all the changes that were saved already inside employee edit view over here because we saved and we returned back the event And if you look on the table tag again, we'll see that we are using new HTMX attributes over here. It's called Tigger. And oh here we need to specify event name employee changed and this is equal to employee change event from here from the post and we specify that we listen for the employee change event from

[38:38] body And body is a root tag in this page and when event is propagated then it'll it will be catch by the body anyway and HTMX will be able to catch the event and when this event happens then the magic HTMX magic happens and it 's able to detect the event And when event is detected, then on top of this table element HTMX get request will be executed And since we don't specify any target here, this means by default target will be the same tag by itself. And

[39:23] Yeah when response comes since we are returning the same template for the for the content then it'll just it means that the current table will be simply replaced Table will be replaced with the new HTML structure and with new data. So it will be re-rendered. And if we go back to the UI and do a couple of more tests, we'll see how it happens. So let's say that we close this block and Let's open Lex, the further employee. And if We go and

[40:09] change the job, maybe as accountant, click Safe yeah it would not work because probably accountant salary is not in range with the current lack salary so it would not work to change we return back it to return back to be administration vice president and if we maybe change the manager to nina Yeah, then it worked. And if you go back we see that the information about the manager was instantly updated to Nina. This means as expected this functionality works great because we work on

### [40:55] Validation Errors and Feedback

[40:55] one section of the screen, do changes there, execute request. And through HTMX events in different areas of the screen we can catch event and refresh the data. Let's look into the error reporting. So there are a few cases when we have we report errors in this application. For example, when we want to update salary to be negative then we get invalid salary must be in range but actually yeah this constraint that is enforcing value to be positive but before that we check salary to be in range also so in this case it's fifteen thousand so if we say that's who would

[41:40] like to update to 10,000 then the same validation error will be displayed also if we change the email to be non-unique value then another validation error is displayed what else did if we try to save data and remove value for the required fields then we'll get field level validation and this out of the box with it comes from those from the plugin which renders the form elements it shows this kind of errors that are defined based on

[42:25] Django model attributes like required one this kind of thing is displayed directly to the on top of the field So we don't need to worry about that. But about other validation errors that enforced on model form or about constraints that are defined on the model we need to think how to report them and in this case we report them below the table just one by one And on the other hand, if we fix the fix it, for example, say this one is sixteen thousand and email will be l The HAN for example we saved and we get the message that

[43:12] message data is saved successfully in this case. So the way how it's implemented, first of all Either successful or error messages are reported from view from the post method for the employee edit view over here. If it's success, then it's included as a Success context either error context and later inside the edit form Here below we got div with feedback and we include partial info HTML. So this is the partial is over here and inside this partial we have two blocks that are wrapped into the Django

[43:58] loops. So first one is loop that displays errors, the second one is that displays success messages. And we are using flow byte styling to display those alerts And yeah, as many error messages we have in a loop we display all of them. If there are none then basically loop is empty and no messages displayed. And this means every time when we return this block for the editable form also info partial is being evaluated and it che we check here if there are any errors then basically text about errors will display it, and if success messages list is not empty, then it also will be displayed.

[44:45] Yeah, so it's quite simple. And this means later on the next request, if we fix validation error and there's no error anymore, then list with errors is empty and it simply doesn't print out any message anymore so this is this is how error handling is done in this application So hopefully yeah it was useful for you and you'll find some practical value for your own use cases. I was trying to keep it as simple and practical as possible. Source code for this application is available on GitHub and yeah it's you can refer to it and try to run

[45:31] application on your own environment and Implement the same stuff for your own use cases. So thanks and yeah, it was a pleasure.
