Django and fieldsets on ModelForm

前端 未结 5 1436
失恋的感觉
失恋的感觉 2020-12-04 10:34

I know you can specify fieldsets in django for Admin helpers. However, I cannot find anything useful for ModelForms. Just some patches which I cannot use. Am I missing somet

5条回答
  •  失恋的感觉
    2020-12-04 10:56

    One thing you can do is break your logical fieldsets into separate model form classes.

    class PersonalInfoForm (forms.ModelForm):
        class Meta:
            model=MyModel
            fields=('field1', 'field2', ...)
    
    class TermsForm (forms.ModelForm):
        class Meta:
            model=MyModel
            fields=('fieldX', 'fieldY', ...)
    

    Pass them to your template in different variables and break up the formsets:

    Personal Information {{ personal_info_form }}
    Terms and Conditions {{ terms_form }}

    In that sense each of your form classes is just a fragment of the actual HTML form.

    It introduces a touch of complexity when you call save on the form. You'll probably want to pass commit=False and then merge the resultant objects. Or just avoid using ModelForm.save altogether and populate your model object by hand with 'cleaned_data'

提交回复
热议问题