From 1159791cd5b706f01e282d6773a17b66b7cdac9f Mon Sep 17 00:00:00 2001 From: Malcolm Tredinnick Date: Thu, 14 Feb 2008 17:38:05 +0000 Subject: Modified [7112] to make things behave more in line with Python subclassing when subclassing ModelForms. Meta can now be subclassed and changes on the child model affect the fields list. Also removed a block of error checking, since it's harder to mess up in unexpected ways now (e.g. you can't change the model and get the entirely wrong fields list), so it was a level of overkill. git-svn-id: http://code.djangoproject.com/svn/django/trunk@7115 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/modelforms.txt | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) (limited to 'docs') diff --git a/docs/modelforms.txt b/docs/modelforms.txt index ec0ecf40cc..b9f0d88165 100644 --- a/docs/modelforms.txt +++ b/docs/modelforms.txt @@ -335,14 +335,19 @@ models. For example, using the previous ``ArticleForm`` class:: This creates a form that behaves identically to ``ArticleForm``, except there is some extra validation and cleaning for the ``pub_date`` field. +You can also subclass the parent's ``Meta`` inner class if you want to change +the ``Meta.fields`` or ``Meta.excludes`` lists:: + + >>> class RestrictedArticleForm(EnhancedArticleForm): + ... class Meta(ArticleForm.Meta): + ... exclude = ['body'] + +This adds in the extra method from the ``EnhancedArticleForm`` and modifies +the original ``ArticleForm.Meta`` to remove one 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 @@ -351,10 +356,3 @@ of concern unless you are trying to do something tricky with subclassing. * 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