2

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?

1 Answer 1

2

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"]
Sign up to request clarification or add additional context in comments.

3 Comments

While this would work, I am trying to compose new forms using multiple inheritance (hence the Mixin). The reason for this is that I have already defined my own base class for forms and I wish to use the AuthorMixin for selected forms only.
You didn't specify that you would like to override from your own base class, in fact your example was that of using a mixin alongside an override of django Form class. I have updated the answer to reflect your needs.
Thank you very much. This is exactly what I needed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.