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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access