4

I'm calling my form, with additional parameter 'validate :

form = MyForm(request.POST, request.FILES, validate=True)

How should I write form's init method to have access to this parameter inside body of my form (for example in _clean method) ? This is what I came up with :

def __init__(self, *args, **kwargs):
    try:
        validate = args['validate']
    except:
        pass           
    if not validate:
        self.validate = False
    elif:
        self.validate = True
    super(MyForm, self).__init__(*args, **kwargs) 

1 Answer 1

9

The validate=True argument is a keyword argument, so it will show up in the kwargsdict. (Only positional arguments show up in args.)

You can use kwargs.pop to try to get the value of kwargs['validate']. If validate is a key in kwargs, then kwargs.pop('validate') will return the associated value. It also has the nice benefit of removing the 'validate' key from the kwargs dict, which makes it ready for the call to __init__.

If the validate key is not in kwargs, then False is returned.

def __init__(self, *args, **kwargs):
    self.validate = kwargs.pop('validate',False)
    super(MyForm, self).__init__(*args, **kwargs)

If you do not wish to remove the 'validate' key from kwargs before passing it to __init__, simply change pop to get.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.