Django & HTMX App - Setup, Models and Management Command

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this series of videos we're going to build a new application using D Jango and HTM X and we're going to build a simple application in this series that allows users to track their financial transactions so we're going to allow users to create transactions view existing transactions as well as to update and delete transactions and as the series progresses we're going to explore more advanced topics like infinite scroll and we'll also look at generating summary statistics for our financial data as well as generating charts and graphs and finally we also look at how to export our data to different formats for example to CSV files now in this series we're going to use jangle as our back end and we're going to use Tailwind CSS and Daisy UI for all of the styling that we need for this application and finally for all interactive content we're going to use HTM X so we're not going to use any other tools like Alpine GS or jQuery or anything like that we're going to stick with htx for the front end and for all of the interactive functionality of this application and as the series on we're also going to dive into testing with P test so we've got a lot to cover let's dive in and get started so let's start with a quick look at the application we have an application called personal finance tracker and let's imagine that you can upload your transactions and store them in this application and you can also edit and delete existing transactions as well now we can view existing transactions by clicking this button here and we're taken to this page that lists out all of the transactions in a table and it has some summary information at the top now the styles on are not amazing in this application but we are going to use Daisy UI in this series and we're just going to use a lot of what that gives you out of the box and you can see we have the option here to add a new transaction and that's going to bring up this form that you see here and we can go back and we can also download and upload transactions to and from a file so for example if you wanted to download this table of transactions you can click this button and it's going to download that for you at the top as you can see here now as well as the table we can also filter these transactions so for example we have categories that are tied to the transaction and if we wanted to only see the transactions associated with two particular categories we can select these two here and then when we click filter it's going to filter that down to only those and I've made this a bit smaller so we can see the whole page better as well as the category filter we can also chain a second filter so for example if we wanted to look at income and not include expenses in this table we can filter down to that as well and when we perform that filter we now get only income with the two categories we selected now all of this interactive functionality is driven by HTM X on the client with Jango on the back end taking those requests and serving up the responses and we have the looking feel of a single page application so when I hit this plus button here we're taken to a form as if it was a single page application but we are actually using HTM X in order to go from one page to the other now when we submit this form we're going to be taken back to the table page here and the new transac action is going to be added to the table and the final thing to show just as an example here at the top we have a tab called my charts so let's click that and we're taken to a page here that contains some simple charts that chart out the expenses and the income and this gives us a way of looking at some summary data for our application for the transactions that we have in our bank account and again these can also be filtered down so if we wanted to select a subset of categories here we can filter down and it's going to generate these charts again as you can see here and this time if we look at the pie charts we are only getting the data for the three categories that we selected now this is not an amazing page it probably wouldn't be built that way in a real application but this is actually using plotly behind the scenes and we're going to learn how to set all of that up later in this series so that's the existing application but we're going to start from some starter code so I'm going to go over to GitHub now and we have a repository here called Django HDMX finance app and this contains some starter code that we're going to clone and we're going to start setting up this project so what I'm going to do is I'm going to copy the URL here and we're going to go to Powershell and you can use any terminal editor you want and we're going to run the get clone command and we're going to clone that repository down to our local computer and once you've cloned that you can CD into the project directory and what I'm going to do is open this up in VSS code and I've got VSS code installed and available on the command line so we can run the code command in the current directory and that's going to open up VSS code and once we've opened that top we can start a python virtual environment on the command line and vs code so I'm going to run python DM and we're going to use the ven module and I'm going to call this environment ven Django HTM X and we can execute that command and it's going to create the environment for us now once we've done that we can activate that environment so I'm going to activate that just now and then if we look at the directory that we've cloned here we have a file called requirements. text and that contains all of the requirements for the starter code now I'm going to install these so let's expand this terminal and we're going to run the PIP install command and we can pass - R and then requirements. text and that's going to install all of these into the virtual environment so you can see this running through that installation now I want to point out a couple of the packages that we've got installed obviously we're using D Jango and I've got D Jango version 4.2 here but if you're following along with this video you can probably upgrade to version 5 everything should still work exactly the same and we're also using Jango allo now the starter code as we're going to see very soon in this video contains login and registration all built in from scratch and that's going to take advantage of the power of Jango Olaf to do that and it's going to mean that we can focus on building the application and we don't need to worry about authentication and we also don't need to worry about registration so as you can see on the terminal we've now got the requirements installed for the starter project we can now go to the application and I'm going to look at the tracker directory and that's the directory that contains or rather that's the jangle app in this project that contains the views.py file and the models.py file and within that we have a templates directory and I'm going to go to base. HTML and because we're going to use HTM X in this series we're going to add HTM X to this file if it's not already there now from the starter code you can see though that we have HDMX it's version 1.9.10 and the second script that we have is linking to a CDN for Tailwind CSS and notice that we also have the type of graphy plugin for Tailwind CSS that's been added to this CDN link here so that should make Tailwind CSS available in this project and we're going to use that we're also going to use Daisy UI which is a component framework built on top of Tailwind CSS so we're going to need to get that into the project as well so what I'm going to do is go to the browser and we have a page on Daisy UI and again there'll be a link to this in the description of this video and if we go to the sidebar here we can go to the installation section and we're going to select a CDN here and we can copy this link that we have to the daisy UI CSS file so let's now add that to the Head tag that we have here in the base. HTML file so we now have Daisy UI and Tailwind available in this project what I'm going to do now is just set up the project so basically we're going to run the migrate command in jangle so let's start by running python manage.py migrate and when we run that it's going to apply all of the migrations and it's going to create the local SQL light database base and at this stage I want to look at models.py the only model that we built or that we have here in this application that's not coming from jangle itself is this user model so we're overriding jango's abstract user and that's a good practice at the start of a jangle project override the default user model and then if you need to add new attributes to the user later on you can do so within this class here it's much harder to change the existing built-in user model after the fact so it's good practice to start with this class here that's overriding either the abstract user or for even more control you can override the abstract base user now that we've run the migrations let's clear the terminal and I'm going to run the Jango development server that's python manage.py run server and we can then go to the browser and we can load up this default site that we have so the default page contains a header tag and it contains some laurum epom text so nothing too exciting going on here but we have the Django oloth login and sign up pages and I've styled these up a little bit using Daisy UI and Tailwind what we can do to start with is sign up to the project so I'm going to create a new user and I'm going to give that user a username of admin and we're going to set up a password here and then we're going to hit sign up and that's going to log us into the application and we have this message appearing here because we're logged in and that's just a welcome message with our username and notice that the nav bar at the top has also changed so whatever the links are on the nav bar depend on whether the user is authenticated or not now this is all built into the starter code so we don't need to worry about any of that now let's move on we're going to go to vs code and we're going to start building the modules for this application so what we're going to do in models.py is we're going to create a new class that I'm going to call transaction and note that this is not a database transaction that we're talking about what we mean here is a financial transaction for example when you go to the store and buy something or when your mortgage payment comes out of your account at the end of the month so this is a financial transaction and it's going to inherit from jango's model class and I'm going to add some notes here about what we want to build so just above the class let's add a comment now a transaction can be either income or an expense and as well as that a transaction has an amount and that's a decimal number a transaction should also be associated with a category and we want that to be a foreign key so we're going to need a category model in this application as well and of course a transaction should also be tied to a user so the authenticated user can add their own transactions to the database but we need a way to associate that transaction with the user that added it so we're going to need a foreign key to the user model and finally as well as that a transaction should have a date so it's useful to know when a transaction occurred and we're going to track that in the transaction model here so let's move on now and we're going to start writing the fields for this model so let's start with the income or expense choices and as the name implies that's going to be a choice field I'm going to paste in a couple of types here so I've got a variable called transaction type choices and we have income and expense as the possible options here so let's now create a field for that and we're going to call this field type so it's going to be called type and it's going to be a models. carfield and we're going to add a max length here of let's say seven and we can set the choices on this field to the transaction type choices that we defined in the class here so that handles the top comment that we have on whether the transaction can be an income or an expense we also need an amount so let's now create a variable called amount and that's going to be equal to a models. decimal field in jangle and the decimal field takes two required arguments Max digits I'm going to set that to 10 and the number of decimal places for this decimal we're going to set that to two because we're working with financial data so the top two are done we are now going to create the foreign Keys let's start with the user model because that already exists in the application so just here I'm going to set the user and that's going to be a models. foreign key and that's a foreign key to that user model and when the user is deleted we're just going to Cascade that delete and also delete all of the users transactions so we also need a category model so I'm going to create that just above the transaction model and it's going to be called category and that's going to inherit from jango's model class now we want to keep the category very simple it's just going to contain a name and that's going to be a car field and we are going to make that unique so that we don't end up with duplicate categories now as well as that I'm going to add a meta class to the category model and we're going to set the verbos name plural field in The Meta class and we're going to set that to categories now if you're wondering why we're doing this what jangle admin is going to do when it sees a model it's going to just add an S to the end of that model that's not the correct pluralization of the word category so what you can do is you can set verbos name plural in the model meta class and that allows you to fix that plural so it appears correctly in the jangle admin and finally in the category model let's quickly Define a Dunder string method that's going to return self. name in other words the name of the category so let's now move on we have the category model we now need to hook up the foreign key to that so on the transaction model we're going to create a field called category and that's going to be a foreign key again this time to category and again on delete let's just Cascade that delete probably not what you want to do in a real application but we'll keep it like that for the series so we can remove that and we have one more comment here for the date so that's when the transaction occurred at the bottom I'm going to add a field called date and we're going to set that to a models. DAT field and that's going to allow the user who's uploading their transactions to set a date for each of those transactions now if you're modeling real financial data you might want to make this a date time field and record the exact time when that transaction occurred but we're not going to do that because it's much simpler in this case to just Define a date field as we'll see later in the series so we now have a date and the final thing to do here is Define the dunder string method for the transaction model so what I'm going to return here is this string that we have on line 31 so it's going to be income or expense of the given amount on the given date and by the given user so let's now go down to the terminal and we're going to stop the server and I'm going to run python manage.py make migrations and that's going to create a migration file for these new changes for the category and the transaction model and when we've done that we can then run the myig great command and that's going to make those changes and add two new tables to the database one for each of the models and let's now go to admin.py within the tracker application so that's here what we're going to do in this file is we're going to register our two new models with the Django admin so let's import the category and transaction models and below this comment we're going to register both of these so that we can edit them in the jangle admin and once we've done that we're going to create a super user in the terminal and that's going to be done with python manage.py create super user so I'm going to call the user bug bites and we're going to select a simple password here and we're going to register like that so I know this is a lot of setup at the moment but we're setting up this application for all of the upcoming videos in this series so we need to have the database ready and we need to have a super user that we can log into to the jangle admin and now that we've done that I want to do one more thing in this video I want to create a jangle management command and that command is going to allow us to populate the database with some data for transactions and categories so that's going to allow us to have some testing data to use when we build this application if you're not interested in this section of the video I'm going to push the code for the management command to GitHub and for each video that we do I'm going to push all of that code into the GitHub repository now if you look at the tracker application in the starter code we have a management/ commands subdirectory and within the commands directory we're going to create a new file and I'm going to call this file generate transactions dopy now we're going to write this code from scratch but as I said if you're not interested in this you can just skip the rest of the video and you can grab this code from GitHub and follow along from the next video but if you are interested in how to generate some fake data in jangle this is one way of doing it so I'm going to paste in some imports here and then we have the skeleton for a jangle management command so we define a class called command that inherits from jango's base command class and the help text says that we are generating some transactions for testing now a command in jangle has a method called handle and when you run the command it's the handle method that's invoked and the logic within that method is what's executed in the command now at the top we've imported the random module from python as well as the faker module and we've also imported the models that we defined in the models.py module so let's now go to the handle method and I'm going to remove the P statement and we're going to start by creating a faker object I'm going to call that fake and we're going to instantiate the faker object and then we're going to start by creating some categories for our application now let's scroll down here to give us some space we're going to start by creating a python list called categories and I'm going to paste some categories in here so I'm not going to go through what these are but you can see that there are common categories for income and expenditure such as bills food and clothes and so on now as you can see here the text is going off the screen so what I'm going to do is use the black code formatter and that's a python code formatter that you can install with Pip and I'm going to run that against the Cent file which is in the management/ commands directory and that's going to reformat the code in this file and as you can see that looks a lot better now we have all of the categories one per line listed out in that python list so what we need to do now is take each of the strings in this list and we need to create a category in the database for each one of those so what I'm going to do here is I'm going to create a for Loop and we're going to Loop over each category in that list of categories and for each one of them what we're going to do is we're going to call category doobs do get or create and get or create is a model manager method in jangle and we're going to pass the name field in here and set it to the category That We're looping over in that for Loop so let's take take the first category of bills it's going to look at the database and try and find a category with that name and if it finds the name it's only going to get it from the database otherwise it's going to create it if it does not exist and that's good for a management command like this because we don't want to try and create duplicates so we can use get or create and if it already exists it's not going to do anything otherwise it's going to create it once we've created all of the categories we're going to get the user from the database that I created so let's create a user variable here and we're going to call user doobs doget and I'm going to pass a username here of bug bites now remember this user here is the one that we created with the create super user command so we're now pulling that user out of the database and you can change the username here if you want to so if you've got a different username for your user you can change it to that here and maybe a better way to do this actually is to get rid of the doget and we're going to use a filter statement here and we're going to filter down to the user with that username and then we can call Dot first and if that user doesn't exist we can check that with this if statement and in that case we can create the user directly with user doobs do creatore super user so create super user is a method on the user model manager in Jango and we can pass the username of bug bites into that and let's give it a very simple password Here of just test and if you didn't know in Django if you have a user model and you call the create super user or create user method it's going to take that plain text password and it's going to Hash it and store that in the database so it's not going to store the pl text password and That's essential for security so at this point we have categories and we have a user in the database what we're going to do now is we're going to create transactions and I want to create 20 of these so I'm going to say for I in range 20 and 20 times we're going to call transaction doobs doc create and we're going to pass in some values here for each field on the transaction model now there's one thing I want to do before we start this I'm going to set a variable here called categories and after we create all of these categories on lines 26 and 27 we can pull them all out into this script here by calling category. objects. all and storing that in a variable called categories now the reason that we want to do that is because when we create a transaction we're going to randomly select one of these categories so let's pass the category keyword in here to the transaction and we're going to use the random module and that has a function called choice and this will choose as it says here a random element from a non-empty sequence and the sequence we're going to pass in is the categories that we got back from the database just above here so that's going to select a random category for the transaction we're also going to tie the transaction to the user that we pulled out with the name of bug bites and let's Now set the amount for this transaction and again we'll use a function function in the python random module and that's random. uniform what this is going to do is give you a random number in the range between A and B so for the transaction amount we're going to put in a random number between 1 and 2,500 and once we've done that we can select the date for this transaction and this is where I want to use the fake object the faker object sorry that I imported just up here so we instantiated this Faker object and we can now use that to get a date and what we're going to do is we're going to use a function on that called date between and this will generate randomly a date between a start date and an end date so the start date that we're going to pass in I'm going to pass in a relative string here of minus one year so that's going to look at the current date when you run this script and it's going to subtract a year from that that's going to be the start date and then of course we have an end date as well and we can pass a string just saying today to that and that's going to select today as the end date so the effect of that line of code is to generate a python date object and that date is going to be sometime in the past year now there's one more field we need to pass into the model and that's the transaction type field and that's going to be one of these choices here so we need to pass in a type let's go back here and we're going to pass that in now and what we need to do is we need to get one of the types from this tiple of Tes so let's copy the name of this and just above the for Loop I'm going to create a variable called types and that's going to be set to a list comprehension in Python and we're going to look at the first element of each tiple for each X in that transaction type choices and that's a field on the transaction model so we need to reference it like that so just to reiterate what's going on here in the transaction type choices we have a tiple for each element with two elements and we only want to get back that first element and what that's going to return is income and expense and it's going to throw away the other two values and that allows us to select either income or expense as the type for the transaction so let's go back here and again we're going to use random. Choice from the random module and we're going to pass those types that we've extracted into that function and I think that's all we need to write here so what we're going to do is bring up the terminal and I'm going to clear this terminal and we're going to run Python manage.py and the name of the script is generate transactions so let's run that just now and we're going to see hopefully that that's going to generate some data for the database now that command has completed we don't see any output and that's because we didn't have any logging in this management command but what we can do is we can try and validate that we have data in the database and I'm on VSS code where I have a SQL light extension an SQL light extension what I'm going to do is rightclick that and I'm going to open the database and if we look at the SQL light Explorer here what we can do is look at the tables that we have in this database now the table that we created was in an app called tracker so let's go down here and I say table I mean multiple tables the one that we're going to look at is the transaction table so let's show that and you can see now we have some transactions appearing in the database here and this has been populated by that management command that we've written in jangle so for example on the first line the transaction is of type expense and it has quite a high amount so that's an expense of 1,945 36 and it has a category ID of five so that's quite a high expense if we look at the category table in this database that should also be populated and you can see the category number five is associated with the housing category so we now have a populated database containing transactions and categories we're now ready to move on in this project and we're going to start displaying these transactions to the users in the next video of the series and we're also going to start integrating HTM X into the project so that's all for this video this has been a setup video and we've created the jangle models and also a management command that's populating the database with data there's lots coming up around HDMX and testing and so on and I'm going to try and release these videos fairly quickly so stay tuned for more videos on this series and you can also find all of the code for this video and for upcoming videos on GitHub so you can check that out as well thanks for watching give the video a thumbs up and subscribe if you're enjoying this content and consider buying the channel at coffee if you're finding this content useful we have a link in the description so thanks again and we'll see you in the next fedu
Info
Channel: BugBytes
Views: 8,949
Rating: undefined out of 5
Keywords:
Id: 6OlILeP9GKg
Channel Id: undefined
Length: 25min 34sec (1534 seconds)
Published: Fri May 03 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.