[Answered ]-Overriding clean() method of Parent django form in child/inherited form

1👍

This line in child class is causing that parent’s clean method is called:

self.cleaned_data=super(MemberAddForm,self).clean()

As the two are almost the same, it looks like the child’s one is not called, i.e. if parent’s clean passes successfully also the child’s one will.

Solution for your problem would be to modify the paren’s clean method to:

   def clean(self, validate_member=True):
        '''
        Grouped cleaning
        '''
        self.cleaned_data=super(NewMemberForm,self).clean()

        if validate_member:
            validate_member_form=validate_member(self.cleaned_data, False)

        # Do we have error messages now?
        if len(validate_member_form[0]) > 0:  # yes we have error messages
            raise forms.ValidationError(_(validate_member_form[0]), code='invalid')

        return validate_member_form[1]

And then all you have to do in child’s clean method is:

def clean(self):
    return super(NewMemberForm,self).clean(validate_member=False)

1👍

There is another option

# dynamic form creation
class CreateUpdateView(FormView):
    template_name = 'apps/frontend/create_update_view.j2'
    def get_form_class(self):
        # url like: /user/(?P<mode>[^/]+)/ - /user/register/ or /user/update/
        is_password_required = self.kwargs.get('mode') == 'register'

        class _Form(forms.Form):
            if is_password_required:
                password = forms.CharField(widget=forms.PasswordInput)

            first_name = forms.CharField(max_length=25, required=True)

        return _Form

Leave a comment