2011年1月21日

django ModelAdmin form submit

記錄一下 django 裡面處理有 inline formset 的 form 時,
它的 calling sequence


假設有下面這樣的 modle and admin:

class SiteInfoForm(ModelForm):
    class Meta:
        model = SiteInfo
    def clean(self):
        print '[debug] site info form clean'
        return super(SiteInfoForm, self).clean()

class SiteAttributeInlineFormset(forms.models.BaseInlineFormSet):
    def clean(self):
        super(SiteAttributeInlineFormset, self).clean()
        print '[debug] site attribute inline formset clean'

class SiteAttributeInline(admin.StackedInline):
    model = SiteAttribute
    formset = SiteAttributeInlineFormset

class SiteInfoAdmin(admin.ModelAdmin):
    inlines = (SiteAttributeInline, DomainPatternInline, )
    form = SiteInfoForm
    def save_formset(self, request, form, formset, change):
        print '[debug] SiteInfoAdmin save formset'
        print type(form)
        print type(formset)
        return super(SiteInfoAdmin, self).save_formset(request, form, formset, change)
    def save_model(self, request, obj, form, change):
        print '[debug] SiteInfoAdmin save model'
        return super(SiteInfoAdmin, self).save_model(request, obj, form, change)


當按下 form 的 submit button 時
debug output 長這樣

[debug] site info form clean
[debug] site attribute inline formset clean
[debug] SiteInfoAdmin save model
[debug] SiteInfoAdmin save formset
<class 'django.forms.models.SiteInfoForm'>
<class 'django.forms.formsets.SiteAttributeFormFormSet'>
[debug] SiteInfoAdmin save formset
<class 'django.forms.models.SiteInfoForm'>
<class 'django.forms.formsets.DomainPatternFormFormSet'>


所以順序是
ModelForm.clean -> InlineFormset.clean -> ModelAdmin.save_model -> ModelAdmin.save_formset

沒有留言:

張貼留言