Opened 11 years ago

Last modified 9 years ago

#10874 new New feature

ModelFormMetaclass does not provide easy way of extending

Reported by: wombat Owned by: nobody
Component: Forms Version: 1.0
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


I am currently creating an extension to the ModelForm that provides similar features to Admin such as fieldsets. Unfortunately, the ModelFormMetaclass does not provide easy way of extending ModelForm. For example, I need to access meta information for fieldsets and dynamicaly flatten to fields before method fields_for_model is called. Also, what if I wanted to override fields for model. There is no way of doing this without completely overriting the entire ModelFormMetaclass. It seems that the meta class approach initialization does not support granual overriding of logic. I have made the following code change to django ModelFormMetaclass to ease my pain for now. However, in the long run it may not be enought.

class ModelFormMetaclass(type):
        options_class = attrs.pop('options_class', ModelFormOptions)
        opts = new_class._meta = options_class(getattr(new_class, 'Meta', None))

The following is the code that uses this:

class DynamicModelFormOptions(ModelFormOptions):
    def __init__(self, options=None):
        self.fieldsets = getattr(options, 'fieldsets', None)
        self.fieldwidths = getattr(options, 'fieldwidths', None)
        if self.fieldsets:
            self.fields = flatten_fieldsets(self.fieldsets)

class DynamicModelFormMetaclass(ModelFormMetaclass):
    def __new__(cls, name, bases, attrs):
        attrs['formfield_callback'] = formfield_for_dbfield
        attrs['options_class'] = DynamicModelFormOptions
        new_class = super(DynamicModelFormMetaclass, cls).__new__(cls, name, bases,
        #new_class._meta = DynamicModelFormOptions(getattr(new_class, 'Meta', None))
        return new_class

Change History (5)

comment:1 Changed 11 years ago by Alex Gaynor

Triage Stage: UnreviewedAccepted

I don't think this is the right approach, but it could be made more modular.

comment:2 Changed 9 years ago by Chris Beaven

Severity: Normal
Type: Bug

comment:3 Changed 9 years ago by Chris Beaven

Type: BugNew feature

On second thoughts, this is more an additional feature.

comment:4 Changed 8 years ago by Aymeric Augustin

UI/UX: unset

Change UI/UX from NULL to False.

comment:5 Changed 8 years ago by Aymeric Augustin

Easy pickings: unset

Change Easy pickings from NULL to False.

Note: See TracTickets for help on using tickets.
Back to Top