-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Stricter type validation for CharField. #4380
Conversation
Breaking change + minor version update 💥 |
Noted. I'd treated it as not a breaking change, given that it'd only be exposed in already broken use-cases. (eg clients posting booleans to a CharField) Still, it's evidently worth us being more conservative in the future, given the large installed base, now. Thanks for the data-point. |
How I override ? :
with
I don't want integers or floats be consider as a valid string . Thanks |
@sergiomb2 Derive a new class from Possibility 1: class MyCharField(CharField):
def to_internal_value(self, data):
if isinstance(data, bool) or not isinstance(data, six.string_types):
self.fail('invalid')
value = six.text_type(data)
return value.strip() if self.trim_whitespace else value Possibility 2: class MyCharField(CharField):
def to_internal_value(self, data):
if isinstance(data, bool) or not isinstance(data, six.string_types):
self.fail('invalid')
return super().to_internal_value(data) # python 3 syntax Do not forget to use your field in your serializers. If you're using the |
many thanks, yes I already use Possibility 1 , but Possibility 2 looks to me even better .
Could you exemplify what you mean ? I think will much more easy to me understand, yes I'd like override all CharFields in the project with MyCharField options , do I need reference all CharField in Serializers class ? Many thanks for the feedback |
class MyModelSerializer(ModelSerializer):
serializer_field_mapping = {
models.AutoField: IntegerField,
models.BigIntegerField: IntegerField,
models.BooleanField: BooleanField,
models.CharField: MyCharField, # ← see here
models.CommaSeparatedIntegerField: MyCharField, # ← see here
models.DateField: DateField,
models.DateTimeField: DateTimeField,
models.DecimalField: DecimalField,
models.EmailField: EmailField,
models.Field: ModelField,
models.FileField: FileField,
models.FloatField: FloatField,
models.ImageField: ImageField,
models.IntegerField: IntegerField,
models.NullBooleanField: NullBooleanField,
models.PositiveIntegerField: IntegerField,
models.PositiveSmallIntegerField: IntegerField,
models.SlugField: SlugField,
models.SmallIntegerField: IntegerField,
models.TextField: MyCharField, # ← see here
models.TimeField: TimeField,
models.URLField: URLField,
models.GenericIPAddressField: IPAddressField,
models.FilePathField: FilePathField,
} Then use |
Thanks , exemplifying a more complete solution :
|
CharField now only accepts string and numeric types, and will raise a validation error on other inputs.
Closes #3394.