by Carl James | BLOOMINGTON, IN | Dec. 29, 2023
Nothing helps a person learn to build applications better than actually doing it. While I love the training resources out there, just following them step-by-step is not enough to even learn basic concepts. Only in the process of building an application with more complex data am I able to get a much better core understanding of what the Python/Django web framework operates.
The training examples I have seen are all of a single model being rendered as a form. Most of the training also has this done with built-in Django classes. While this is functional and easy to type, it didn't help to learn what a form truly was. My initial mental image was a reflection of the data model.
I ran into a new challenge that wasn't solved by this thinking. I wanted to be able to update two different models with a single click. At first I thought about using a cascade of HTMX calls on the front end to send multiple form posts. That introduced another problem, because although the two model objects I wanted to create were different, they are also related by a foreign key.
After stepping away and coming back, I looked at the code:
It then dawned on me. The form does not need to be limited to the structure of a single model. It can fill and submit any data I want it to. Then I can use that data to create multiple model objects, which is a Django way of saying rows in the database.
More importantly I can then use the
.last() syntax to pull the primary key one model object to automatically add it as a foreign key the other object. This is all done with one form and one submission.
While yes it works, what it really did was make it more conceptually clear to me what a form in Django really is. It is a Python contruct that renders input fields in HTML that create a data object to be sent the server. Once the server has the data, the server can do anything it is programmed to do with that data. While forms are often just mirrors of data models, they don't have to be. Even though I've done Python web work on the side for over five years and Django for three years, I never really understood this concept until today.
I'm calling that a big win.
I have more I want to do with my application. Most of the current functionality is covered by my suite of 15 tests. My goals include:
I will come back periodically to update on the application development process.