Django forms - append to class meta exclude and widgets

泄露秘密 提交于 2019-12-21 13:10:23

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/7251697/django-forms-append-to-class-meta-exclude-and-widgets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!