88except ImportError as exc : # pragma: no cover
99 raise ImportError ("Package 'Django' is required to use this module." ) from exc
1010
11- from typing import Any , Optional , Tuple
11+ from typing import Any , ClassVar , Optional , Tuple
1212
1313import django .core .exceptions
1414import django .db .models
@@ -41,7 +41,6 @@ class RutField(django.db.models.Field):
4141
4242 """
4343
44- # TODO: add option to validate that "digito verificador" is correct.
4544 # TODO: implement method 'formfield'. Probably a copy of 'CharField.formfield' is fine.
4645
4746 description = 'RUT for SII (Chile)'
@@ -50,8 +49,18 @@ class RutField(django.db.models.Field):
5049 'invalid_dv' : "\" digito verificador\" of RUT '%(value)s' is incorrect." ,
5150 }
5251 empty_strings_allowed = False
52+ validate_dv_by_default : ClassVar [bool ] = False
53+
54+ def __init__ (
55+ self ,
56+ verbose_name : Optional [str ] = None ,
57+ name : Optional [str ] = None ,
58+ validate_dv : bool = validate_dv_by_default ,
59+ * args : Any ,
60+ ** kwargs : Any ,
61+ ) -> None :
62+ self .validate_dv = validate_dv
5363
54- def __init__ (self , * args : Any , ** kwargs : Any ) -> None :
5564 # note: the value saved to the DB will always be in canonical format.
5665 db_column_max_length = cl_sii .rut .constants .RUT_CANONICAL_MAX_LENGTH
5766
@@ -62,7 +71,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
6271 raise ValueError ("This field does not allow customization of 'max_length'." )
6372
6473 kwargs ['max_length' ] = db_column_max_length
65- super ().__init__ (* args , ** kwargs )
74+ super ().__init__ (verbose_name , name , * args , ** kwargs )
6675
6776 def deconstruct (self ) -> Tuple [str , str , Any , Any ]:
6877 """
@@ -71,6 +80,10 @@ def deconstruct(self) -> Tuple[str, str, Any, Any]:
7180 # note: this override is necessary because we have a custom constructor.
7281
7382 name , path , args , kwargs = super ().deconstruct ()
83+
84+ if self .validate_dv != self .validate_dv_by_default :
85+ kwargs ['validate_dv' ] = self .validate_dv
86+
7487 del kwargs ['max_length' ]
7588
7689 return name , path , args , kwargs
@@ -144,8 +157,19 @@ def to_python(self, value: Optional[object]) -> Optional[Rut]:
144157 converted_value = value
145158 else :
146159 try :
147- converted_value = Rut (value , validate_dv = False ) # type: ignore
148- except (AttributeError , TypeError , ValueError ):
160+ converted_value = Rut (value , validate_dv = self .validate_dv ) # type: ignore
161+ except (AttributeError , TypeError , ValueError ) as exc :
162+ if (
163+ isinstance (exc , ValueError )
164+ and exc .args
165+ and exc .args [0 ] == Rut .INVALID_DV_ERROR_MESSAGE
166+ ):
167+ raise django .core .exceptions .ValidationError (
168+ self .error_messages ['invalid_dv' ],
169+ code = 'invalid_dv' ,
170+ params = {'value' : value },
171+ )
172+
149173 raise django .core .exceptions .ValidationError (
150174 self .error_messages ['invalid' ],
151175 code = 'invalid' ,
0 commit comments