Class BooleanField (Field): empty_strings_allowed = False default_error_messages = {'invalid': _ (u "'% s' value must be either True or False. "),} description = _ (" Boolean (Either True or False) ") def _ init _ (self, * args, ** kwargs ): kwargs ['Blank '] = True if 'default' not in kwargs and not kwargs. get ('null'): kwargs ['default'] = False Field. _ init _ (self, * args, ** kwargs) def get_internal_type (self): return "BooleanField" def to_python (self, value): if value in (True, false): # if value is 1 or 0 than it's equal to True or False, but we want # to return a true bool for semantic reasons. return bool (value) if value in ('t', 'true', '1'): return True if value in ('F', 'false', '0 '): return False msg = self. error_messages ['invalid'] % str (value) raise exceptions. validationError (msg) def get_prep_lookup (self, lookup_type, value): # Special-case handling for filters coming from a Web request (e.g. the # admin interface ). only works for scalar values (not lists ). if you're # passing in a list, you might as well make things the right type when # constructing the list. if value in ('1', '0'): value = bool (int (value) return super (BooleanField, self ). get_prep_lookup (lookup_type, value) def get_prep_value (self, value): if value is None: return None return bool (value) def formfield (self, ** kwargs ): # Unlike most fields, BooleanField figures out include_blank from # self. null instead of self. blank. if self. choices: include_blank = (self. null or not (self. has_default () or 'initial' in kwargs) ULTS = {'choices': self. get_choices (include_blank = include_blank)} else: defaults = {'form _ class': forms. booleanField} defaults. update (kwargs) return super (BooleanField, self ). formfield (** defaults)
It seems that BooleanField is much more complicated. We only analyze
To_python functions
1 def to_python (self, value): 2 if value in (True, False): 3 # if value is 1 or 0 than it's equal to True or False, but we want 4 # to return a true bool for semantic reasons. 5 return bool (value) 6 if value in ('t', 'true', '1'): 7 return True 8 if value in ('F', 'false ', '0'): 9 return False10 msg = self. error_messages ['invalid'] % str (value) 11 raise exceptions. validationError (msg)
The function obtains a parameter value and determines whether the value is one of (True, False, 1, 0). If yes, True or False is returned.
Similarly, if the value is a string, True is returned if the value is one of ('t', 'true', '1...
If msg = XXXXX is executed, to_python fails to be executed and an error is returned... an exception is thrown...
Note that:
>>> A = True >>> B = False >>> c = 1 >>> d = 0 >>> e = 11 >>> f =-1 >>> a in (True, false) True >>> B in (True, False) True >>> c in (True, False) True >>> d in (True, False) true >>> e in (True, False) False >>> f in (True, False) False >>>
If the number is greater than 1, it will not be in (True, False).
>>> If 11: print 'A' aa >>>
Is different.
Django source code parsing BooleanField (2)