Skip to content

Commit

Permalink
Handle primitive types in serializerfields
Browse files Browse the repository at this point in the history
Avoid crashes because the to_python helper expects data to be provided
as string.
  • Loading branch information
francoisfreitag committed Aug 27, 2022
1 parent 4aeb786 commit 46dd7b4
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
3 changes: 2 additions & 1 deletion phonenumber_field/serializerfields.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ class PhoneNumberField(serializers.CharField):
default_error_messages = {"invalid": _("Enter a valid phone number.")}

def to_internal_value(self, data):
phone_number = to_python(data)
str_value = super().to_internal_value(data)
phone_number = to_python(str_value)
if phone_number and not phone_number.is_valid():
raise ValidationError(self.error_messages["invalid"])
return phone_number
13 changes: 13 additions & 0 deletions tests/test_serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from django.test import SimpleTestCase
from rest_framework import serializers

from phonenumber_field.serializerfields import PhoneNumberField


class PhoneNumberFieldTest(SimpleTestCase):
def test_int(self):
class PhoneNumberSerializer(serializers.Serializer):
phone = PhoneNumberField()

s = PhoneNumberSerializer(data={"phone": 1})
self.assertIs(s.is_valid(), False)
1 change: 1 addition & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ deps =
dj32: Django>=3.2,<4.0
dj40: Django>=4.0,<4.1
djmain: https://github.com/django/django/archive/main.tar.gz
djangorestframework
extras = phonenumberslite
commands =
coverage run --source phonenumber_field -m django test --settings=tests.settings {posargs}
Expand Down

0 comments on commit 46dd7b4

Please sign in to comment.