- Django 3 Web Development Cookbook
- Aidas Bendoraitis Jake Kronika
- 147字
- 2025-04-04 13:15:08
How it works...
Let's take a look at the form. At first, we exclude the author field from the form because we want to handle it programatically. We overwrite the __init__() method to accept HttpRequest as the first parameter and store it in the form. The save() method of a model form handles the saving of the model. The commit parameter tells the model form to save the instance immediately or otherwise to create and populate the instance, but not save it yet. In our case, we get the instance without saving it, then assign the author from the current user. Finally, we save the instance if commit is True. We will call the dynamically added save_m2m() method of the form to save many-to-many relations, for example, categories.
In the view, we just pass the request variable to the form as the first parameter.