-
Notifications
You must be signed in to change notification settings - Fork 315
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement region argument for serializerfields
The region argument was implemented for the database field and form field, but not the Django REST framework serializers. Align the serializer with the other fields. Add a bunch of tests for that field.
- Loading branch information
1 parent
b746061
commit 1f012e4
Showing
2 changed files
with
81 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,22 @@ | ||
from django.conf import settings | ||
from django.utils.translation import gettext_lazy as _ | ||
from rest_framework import serializers | ||
from rest_framework.exceptions import ValidationError | ||
|
||
from phonenumber_field.phonenumber import to_python | ||
from phonenumber_field.phonenumber import to_python, validate_region | ||
|
||
|
||
class PhoneNumberField(serializers.CharField): | ||
default_error_messages = {"invalid": _("Enter a valid phone number.")} | ||
|
||
def __init__(self, *args, region=None, **kwargs): | ||
super().__init__(*args, **kwargs) | ||
validate_region(region) | ||
self.region = region or getattr(settings, "PHONENUMBER_DEFAULT_REGION", None) | ||
|
||
def to_internal_value(self, data): | ||
str_value = super().to_internal_value(data) | ||
phone_number = to_python(str_value) | ||
phone_number = to_python(str_value, region=self.region) | ||
if phone_number and not phone_number.is_valid(): | ||
raise ValidationError(self.error_messages["invalid"]) | ||
return phone_number |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters