Created
January 22, 2016 11:53
-
-
Save tomchristie/6c61418027630a1f0308 to your computer and use it in GitHub Desktop.
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
class CountryCodeField(serializers.Field): | |
codes = {'US': 45, 'AU': 12} | |
def to_internal_value(self, value): | |
# make sure it is a string | |
if type(value) is not str: | |
raise ValidationError('`value` must be a string, you sent type %s' % type(value)) | |
# check length | |
if len(value) != 2: | |
raise ValidationError('value must be a 2 character ISO code, you sent %s' % value) | |
try: | |
return self.codes[value.upper()] | |
except KeyError: | |
raise ValidationError('Not a valid country code') | |
def to_representation(self, value): | |
inverse_lookup = dict([(numeric_id, code) for (code, numeric_id) in self.codes.items()]) | |
return inverse_lookup[value] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment