Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django forms - append to class meta exclude and widgets

Is it possible to append to the exclude or widgets variables of an inherited Form?

I have the following set up so far.

class AddPropertyForm(forms.ModelForm):
    num_months = forms.ChoiceField(choices=MONTHS)
    request_featured = forms.BooleanField(required=False)
    featured_months = forms.ChoiceField(choices=MONTHS)

    class Meta():
        model = RentalProperty
        exclude = ('listing_id', 'active_listing', 'active_listing_expiry_date', 'featured_property', 'featured_expiry_date', 'slug', 'property_manager')
        widgets = {
            'property_type': forms.Select(attrs={'onchange':'propertyType()'}),
        }

class EditPropertyForm(AddPropertyForm):
    request_reactivation = forms.BooleanField(required=False)
    class Meta(AddPropertyForm.Meta):
        exclude = ('address1', 'property_type')
        widgets = {
            'request_reactivation': forms.CheckboxInput(attrs {'onchange':'reactivateProperty()'}),
        }

I am trying to get the end result for EditPropertyForm to look like the following for the exclude and widgets statements.

exclude = ('address1', 'property_type', 'listing_id', 'active_listing', 'active_listing_expiry_date', 'featured_property', 'featured_expiry_date', 'slug', 'property_manager')

widgets = {
    'request_reactivation': forms.CheckboxInput(attrs {'onchange':'reactivateProperty()'}),
    'property_type': forms.Select(attrs={'onchange':'propertyType()'}),
}

If there is a better approach, please suggest.

Any help is most appreciated.

like image 421
bmeyer71 Avatar asked Aug 31 '11 01:08

bmeyer71


1 Answers

What about grabbing the properties from the parent Meta class and updating them?

Something like this (untested):

class Meta(AddPropertyForm.Meta):
    exclude = tuple(list(AddPropertyForm.Meta.exclude) + ['address1', 'property_type'])
    widgets = AddPropertyForm.Meta.widgets.copy()
    widgets.update({
        'request_reactivation': forms.CheckboxInput(attrs {'onchange':'reactivateProperty()'}),
    })

It's not pretty, but should get you what you want.

like image 183
Sam Dolan Avatar answered Sep 28 '22 06:09

Sam Dolan