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 work because I want to be able to use other forms as base classes like so:
class NoteFormMixin(object): note = forms.CharField() class MainForm(forms.Form): name = forms.CharField() age = forms.IntegerField() class SpecialForm(MainForm, NoteFormMixin): favorite_color = forms.CharField()
My only question is: how does this work? So far it looks like if I use a mixin, then it doesn't recognize the fields set from that mixin:
>>> ff1 = SpecialForm() >>> ff1.fields {'name': <django.forms.fields.CharField object at 0x178d3110>, 'age': <django.forms.fields.IntegerField object at 0x178d3190>, 'favorite_color': <django.forms.fields.CharField object at 0x178d3210>}
Is this just something that can't be done?
In object-oriented programming languages, a mixin is a class which contains a combination of methods from other classes. Add timestamp and trashed attribute for every model object - This was one of the most important thing that we should have been implemented as early as possible.
It's perfectly valid for a mixin to inherit from another mixin - in fact, this is how most of Django's more advanced mixins are made. However, the idea of mixins is that they are reusable parts that, together with other classes, build a complete, usable class.
The issue is that your NoteFormMixin is deriving from object instead of forms.Form. You need to change it to be like so:
class NoteFormMixin(forms.Form): note = forms.CharField()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With