Skip to content

Instantly share code, notes, and snippets.

@tomchristie
Created January 22, 2016 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomchristie/6c61418027630a1f0308 to your computer and use it in GitHub Desktop.
Save tomchristie/6c61418027630a1f0308 to your computer and use it in GitHub Desktop.
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