__init__ method for the form with optional arguments

I invoke my form with the optional parameter "validate:

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

How can I write an init form to have access to this parameter inside the body of my form (for example, in the _clean method)? Here 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) 
+4
source share
1 answer

The validate=True argument is a keyword argument, so it will be displayed in kwargs dict. (Only positional arguments are displayed in args .)

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

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

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

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

+9
source

Source: https://habr.com/ru/post/1314903/


All Articles