Django

Code

Ticket #7018 (new)

Opened 1 year ago

Last modified 4 months ago

Make ModelForm multiple inheritance is possible.

Reported by: bear330 Assigned to: nobody
Milestone: Component: Forms
Version: SVN Keywords:
Cc: robillard.etienne@gmail.com Triage Stage: Design decision needed
Has patch: 0 Needs documentation: 0
Needs tests: 0 Patch needs improvement: 0

Description

If I have two ModelForm?:

class AForm(ModelForm):
    class Meta:
        model = A

class BForm(ModelForm):
    class Meta:
        model = B

class CForm(AForm, BForm):
    pass

This doesn't work because of the code:

        declared_fields = get_declared_fields(bases, attrs, False)

in ModelFormMetaclass?.

I can to this to make it work:

# Because ModelFormMetaclass will call get_declared_fields method with
# with_base_fields=False, we modify it with True.
from django.newforms import models as nmodels
gdf = nmodels.get_declared_fields
nmodels.get_declared_fields = \
    lambda bases, attrs, with_base_fields: gdf(bases, attrs, True)

But it will be nice if this behavior is default behavior.

Thanks.

Attachments

Change History

(follow-up: ↓ 4 ) 04/14/08 12:19:12 changed by bear330

  • needs_better_patch changed.
  • needs_tests changed.
  • needs_docs changed.

A reference about form multiple inheritance:

http://www.djangosnippets.org/snippets/703/

05/10/08 09:32:32 changed by erob

  • cc set to robillard.etienne@gmail.com.

07/02/08 07:01:44 changed by garcia_marc

  • milestone set to post-1.0.

(in reply to: ↑ 1 ) 07/12/08 06:09:08 changed by bear330

After [7846], that this way to make ModelForm? be able to multiple inheritance is invalid.

New way to make it work is:

def getMixupFormMetaClass():
    """
    Get metaclass for form class that inherits multiple forms, especially the
    base classes of form mix up with Form and ModelForm (metaclass mix up with
    DeclarativeFieldsMetaclass, ModelFormMetaclass).
    See http://code.djangoproject.com/ticket/7018 for related details.
    @return Function that will generate class that metaclass will do.
    """
    from django.newforms import models as nmodels
    factory = classmaker()
    def new(name, bases, attrs):
        # get_declared_fields can only be called once, the result will be wrong
        # if you call it again. We call it first to hold the correct result.
        fields = nmodels.get_declared_fields(bases, attrs, True)
        newclass = factory(name, bases, attrs)
        # Restore the correct result.
        newclass.base_fields = fields
        return newclass
    return new

08/08/08 15:51:37 changed by ericholscher

  • stage changed from Unreviewed to Design decision needed.

02/25/09 13:51:44 changed by

  • milestone deleted.

Milestone post-1.0 deleted


Add/Change #7018 (Make ModelForm multiple inheritance is possible.)




Change Properties
Action