Using a mixin with a Django form class

后端 未结 4 2038
眼角桃花
眼角桃花 2020-12-29 04:06

I\'m thinking about creating a mixin form class so that I can add a common set of fields to a variety of otherwise very different forms. Just using it as a base class won\'t

4条回答
  •  执笔经年
    2020-12-29 04:47

    Just providing some clarity on @Adam Dobrawy's answer, which helped me:

    This doesn't work:

    class NoteFormMixin(object):
        note = forms.CharField()
    

    This does:

    class NoteFormMixin(object):
        def __init__(self, *args, **kwargs):
            super(NoteFormMixin, self).__init__(*args, **kwargs)
            self.fields['note'] = forms.CharField()
    

    This behaviour is probably related to how django collects fields during class instantiation or something.. I haven't bothered to get into weeds of it. I just found this tidbit lets me write my mixin in nice readable way, without any extra django-form-specific crud.

提交回复
热议问题