Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a mixin with a Django form class

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?

like image 209
Jordan Reiter Avatar asked Aug 18 '11 22:08

Jordan Reiter


People also ask

What is Django mixin?

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.

Can a mixin inherit from another mixin?

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.


1 Answers

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() 
like image 155
Patrick Altman Avatar answered Oct 25 '22 23:10

Patrick Altman