shayms8
shayms8

Reputation: 771

Django - How to use the exact same clean() method on multiple forms

I have multiple forms that uses the same clean() and clean_<field_name>() methods.

My problem is that i write the exact same code for all my forms, something like:

forms.py

class FirstForm(forms.Form):
    ...

    clean():
        <long clean code that repeats on all forms>

    clean_field1():
        <clean_field1 code that repeats on all forms>

class SecondForm(forms.Form):
    ...

    clean():
        <long  clean code that repeats on all forms>

    clean_field1():
        <clean_field1 code that repeats on all forms>

class ThirdForm(forms.Form):
    ...

    clean():
        <long  clean code that repeats on all forms>

    clean_field1():
        <clean_field1 code that repeats on all forms>

So my question is what it the best approach to write those clean() methods on 1 place and just call them on different forms?

Upvotes: 1

Views: 474

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476740

You subclass. You first make an abstract form:

class SomeBaseForm(forms.Form):
    # ...

    clean():
        # long clean code that repeats on all forms
        pass

    clean_field1():
        # clean_field1 code that repeats on all forms
        pass

and then you subclass that SomeBaseForm in the forms:

class FirstForm(SomeBaseForm):
    # ...

class SecondForm(SomeBaseForm):
    # ...

class ThirdForm(SomeBaseForm):
    # ...

So here the FirstForm, SecondForm and ThirdForm will inherit from the SomeBaseForm the clean and clean_field1 method.

If you want to inherit (and change) the Meta class, you can do that as well. For example:

class SomeBaseForm(forms.Form):
    # ...

    class Meta:
        model = SomeModel
        fields = ['name']

and then we can subclass like:

class FirstForm(SomeBaseForm):
    # ...

    class Meta(SomeBaseForm.Meta):
        fields = ['name', 'description']

Upvotes: 2

Related Questions