Reputation: 6004
I have two forms NewItem(ModelForm)
and EditItem(ModelForm)
. I overrode the clean()
method of NewItem(ModelForm)
to validate the fields. I would like to re-use the same clean()
method in EditItem(ModelForm)
incase the use tries to edit and re-save the data? Is there a clean way to achieve this without copy and paste?
Upvotes: 2
Views: 766
Reputation: 47866
Yes, you can create a mixin class named FormCleanMixin()
which will contain the clean()
method common between the 2 forms. Then inherit this mixin class in your 2 forms.
First, create the mixin class like:
from django.forms import ModelForm
class FormCleanMixin(ModelForm):
def clean(self):
...
# your common code for 'clean()' here
Now, inherit this mixin class in your two forms like:
class NewItem(FormCleanMixin): # inherit the mixin
... # your code
class EditItem(FormCleanMixin): # inherit the mixin
... # your code
Upvotes: 4
Reputation: 470
You could use inheritance for that:
EditItem
inherit from NewItem
: EditItem(NewItem)
clean()
method, for example CleanItemForm(ModelForm)
, and then you defineNewItem(CleanItemForm)
and EditItem(CleanItemForm)
.Note: I'm new to Django and there may be another method that I don't know about.
Upvotes: 1