Emmanuel Osimosu
Emmanuel Osimosu

Reputation: 6004

How to use the same clean() method in two different forms in django?

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

Answers (2)

Rahul Gupta
Rahul Gupta

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

Xebax
Xebax

Reputation: 470

You could use inheritance for that:

  • make EditItem inherit from NewItem: EditItem(NewItem)
  • or both forms inherit from a class that defines only the 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

Related Questions