Search code examples
pythondjangomultiple-inheritance

How can I use multiple inheritance to compose Django forms?


I have lots of forms which contain the same non-model field. For the sake of this example, let's call the field author. This is not a field of any model, just a field that I want to appear in each form. Here is a working example of my current code:

from django import forms
from . import models

class BlogForm(forms.Form):
    author = forms.CharField()
    class Meta:
        model = models.Blog
        fields = ["author"]

class BookForm(forms.Form):
    author = forms.CharField()
    class Meta:
        model = models.Book
        fields = ["author"]

So, naturally, I thought I could use Python inheritance and create a reusable "mixin" class that contains this field. However, it seems that this is not possible. For some reason, I can't get the following to work:

from django import forms
from . import models

class AuthorMixin:
    author = forms.CharField()

class BookForm(AuthorMixin, forms.Form):
    class Meta:
        model = models.Book
        fields = ["author"]

This is the error I'm getting:

django.core.exceptions.FieldError: Unknown field(s) (author) specified for Book

How can I use multiple inheritance to compose Django forms?


Solution

  • Your AuthorMixin class should override forms.Forms:

    class AuthorMixin(forms.Form):
        author = forms.CharField()
    
    class BookForm(AuthorMixin, forms.Form):
        class Meta:
            model = models.Book
            fields = ["author"]