0

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?

Pavel Antspovich
  • 1,111
  • 1
  • 11
  • 27

1 Answers1

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