Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__init__ method for form with additional arguments

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) 
like image 923
muntu Avatar asked Jan 22 '23 19:01

muntu


1 Answers

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.

like image 101
unutbu Avatar answered Jan 29 '23 10:01

unutbu