user1039384
user1039384

Reputation: 521

How to exclude fields from django forms.Form?

I guess this is another simple question on django forms that I am struggling to find an answer for.

Say I have the following

class Form1(forms.Form):
    a=forms.CharField( label=_("A"),max_length=40)
    b=forms.CharField( label=_("B"),max_length=40)

class Form2(forms.Form):
   c=forms.CharField( label=_("C"),max_length=40)
   d=forms.CharField( label=_("D"),max_length=40)

class Form3(Form1,Form2):

    def __init__(self, *args, **kw):
        Form1.__init__(self,*args, **kw)
        Form2.__init__(self,*args, **kw)

#Here I don't want to have a from Form1
# how can I exclude it so that validation does not bark??

I tried exclude=(a,) in Meta class defined in Form3 but does not work, form validation keeps failing form me.

Thanks in advance

Upvotes: 2

Views: 4147

Answers (2)

Dhruvil Amin
Dhruvil Amin

Reputation: 831

You can override the field and set it to None

class Form3(Form1,Form2):

a = None

Below is the reference: https://code.djangoproject.com/ticket/8620#no1

Upvotes: 1

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53998

Have you tried:

def __init__(self, *args, **kwargs):
    super(Form3, self).__init__(*args, **kwargs)
    del self.fields['a']

Upvotes: 4

Related Questions