HTMX + Django: Modern Python Web Apps, Hold the JavaScript Transcripts
Chapter: Feature 1: Click-to-edit
Lecture: Adding post handling to the category view
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
I'm going to use a ModelForm class to do the processing of the submission, so at the top here I need to add an import.
0:11
As the form for the video closely maps to the model for the video, I'm going to use
0:16
the ModelFormFactory function to quickly create a ModelForm object for me.
0:21
OK, I've got a ModelForm now, time to actually change the view. Let me scroll down a bit.
0:41
Currently, this view only handles the default get mode, but to handle form submission it needs to deal with post as well.
0:50
To keep the code simple, I'm going to create a form in both get and post mode. I'm not actually going to use it in get, but that's just laziness.
0:59
A better implementation would use the form inside the HTML and then write if-else blocks to get placeholder attributes to work properly.
1:08
this isn't a tutorial on good HTML so I'm going to be a bit naughty and keep the example shorter. I'm using a default empty form in the Get mode
1:36
And in the Post mode, I'm processing the submitted content, validating it, then using the form's Save method to turn it into a model object.
1:47
I then add the category relationship to that newly created video.
1:52
Again, a more robust example would include some error handling, especially down in the
1:57
HTML, but there's not much that can go wrong in this case if the user is actually using the form.
2:04
In the real world, you should never assume that the user is using the form, but for our purposes it's good enough.
2:11
If you were going to do that kind of error processing in the HTML, you'd need the form sent down to the template.
2:18
Let's put it in there, with the promise that we'll come back and be better coders later. *cough* Sorry, had to stifle a little bit of a giggle there.
2:27
I'll fire up the dev server here. Switch to the browser. Let's go down to the Python area here.
2:47
Scroll down. And there's our form. Let me try to add something here. There you go, the page is reloaded. And I've got a new video.
3:05
Excellent. All set to switch this over to HTMX.