7.3.7 Using ModelForm
Inheritance to Connect TagForm
to Tag
We could now move on to our other forms, as our TagForm
is fully functional. However, consider that to create our TagForm
class, we reproduced the structure of our Tag
model with form fields. Should we add or modify a field in Tag
, we would need to mirror our actions in TagForm
. We can avoid this scenario and maintain DRY if we connect TagForm
to Tag
. By changing the inheritance of TagForm
from forms.Form
to forms.ModelForm
and connecting TagForm
to Tag
via a Meta
nested class attribute, not only can we remove the list of declared form fields, but we can also remove the save()
method, as it is now automatically provided to us. In /organizer/forms.py
, we would thus have the code shown ...
Get Django Unleashed now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.