I have a model form with a few fields. In one template I want to use all of these fields in one template and exlude a certain field in another. Is it possible not to write new form and just exclude this field in views.py
?
Asked
Active
Viewed 52 times
0

Pavel Antspovich
- 1,111
- 1
- 11
- 27
1 Answers
1
Not exactly, but you don't have to repeat yourself.
You can define a base form containing all the fields you always use, and inherit from it to add fields
class MyPersonBaseForm( forms.Form):
surname = forms.CharField( max_length=100)
forenames = ...
age = ...
company = ...
...
class MyFooPersonForm( MyPersonBaseForm):
foo =
and MyFooPersonForm
has all the fields of MyPersonForm
plus foo
You can also remove fields from a form subclass using its __init__
method, as per this post (garnertb's relevant answer pasted below)
class LoginFormWithoutNickname(LoginForm):
def __init__(self, *args, **kwargs):
super(LoginFormWithoutNickname, self).__init__(*args, **kwargs)
self.fields.pop('nickname')

nigel222
- 7,582
- 1
- 14
- 22
-
This is my plan B) – Pavel Antspovich Oct 29 '19 at 16:40
-
@pavel_antspovich you can also declare all the fields in the base form and selectively remove them in the subclasses. Have edited my answer. You might even mix the techniques, but that soon gets confusing. – nigel222 Oct 29 '19 at 17:12