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)
The validate=True
argument is a keyword argument, so it will show up in the kwargs
dict. (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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With