Reputation: 771
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
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