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=Trueargument is a keyword argument, so it will show up in thekwargsdict. (Only positional arguments show up inargs.)You can use kwargs.pop to try to get the value of
kwargs['validate'].If
validateis a key inkwargs, thenkwargs.pop('validate')will return the associated value. It also has the nice benefit of removing the'validate'key from thekwargsdict, which makes it ready for the call to__init__.If the
validatekey is not inkwargs, thenFalseis returned.If you do not wish to remove the
'validate'key fromkwargsbefore passing it to__init__, simply changepoptoget.