From 37962ecea79cb9d296645a5324cd91818fed65b3 Mon Sep 17 00:00:00 2001 From: Malcolm Tredinnick Date: Thu, 14 Feb 2008 12:56:49 +0000 Subject: Fixed #6337. Refs #3632 -- Fixed ModelForms subclassing, to the extent that it can be made to work. This ended up being an almost complete rewrite of ModelForms.__new__, but should be backwards compatible (although the text of one error message has changed, which is only user visible and only if you pass in invalid code). Documentation updated, also. This started out as a patch from semenov (many thanks!), but by the time all the problems were hammered out, little of the original was left. Still, it was a good starting point. git-svn-id: http://code.djangoproject.com/svn/django/trunk@7112 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/modelforms.txt | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) (limited to 'docs') diff --git a/docs/modelforms.txt b/docs/modelforms.txt index a99e27fff7..ec0ecf40cc 100644 --- a/docs/modelforms.txt +++ b/docs/modelforms.txt @@ -320,3 +320,41 @@ parameter when declaring the form field:: ... ... class Meta: ... model = Article + +Form inheritance +---------------- +As with the basic forms, you can extend and reuse ``ModelForms`` by inheriting +them. Normally, this will be useful if you need to declare some extra fields +or extra methods on a parent class for use in a number of forms derived from +models. For example, using the previous ``ArticleForm`` class:: + + >>> class EnhancedArticleForm(ArticleForm): + ... def clean_pub_date(self): + ... ... + +This creates a form that behaves identically to ``ArticleForm``, except there +is some extra validation and cleaning for the ``pub_date`` field. + +There are a couple of things to note, however. Most of these won't normally be +of concern unless you are trying to do something tricky with subclassing. + + * All the fields from the parent classes will appear in the child + ``ModelForm``. This means you cannot change a parent's ``Meta.exclude`` + attribute, for example, and except it to have an effect, since the field is + already part of the field list in the parent class. + + * Normal Python name resolution rules apply. If you have multiple base + classes that declare a ``Meta`` inner class, only the first one will be + used. This means the child's ``Meta``, if it exists, otherwise the + ``Meta`` of the first parent, etc. + + * For technical reasons, you cannot have a subclass that is inherited from + both a ``ModelForm`` and a ``Form`` simultaneously. + +Because of the "child inherits all fields from parents" behaviour, you +shouldn't try to declare model fields in multiple classes (parent and child). +Instead, declare all the model-related stuff in one class and use inheritance +to add "extra" non-model fields and methods to the final result. Whether you +put the "extra" functions in the parent class or the child class will depend +on how you intend to reuse them. + -- cgit v1.3