Subclassing Django ModelForms

后端 未结 1 1905
南方客
南方客 2021-02-12 19:52

I want to extend ModelForms with the main purpose of adding fields to the form. I think it is easier to see with an example:

# Basic listing
class BasicForm(Mode         


        
相关标签:
1条回答
  • 2021-02-12 20:30

    This is a late answer, but I wanted to note that you can subclass the inner Meta class like this:

    class SocialForm(BasicForm):
        class Meta(BasicForm.Meta):
            fields = BasicForm.Meta.fields + ('facebook', 'twitter')
    

    That way you don't have to repeat the model = Business definition, and any other Meta attributes you may add to BasicForm will automatically be inherited by SocialForm.

    For reference, here's the Django documentation on this approach.

    0 讨论(0)
提交回复
热议问题