Created
November 30, 2013 11:30
-
-
Save meoooh/7717938 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 UserSerializer(serializers.ModelSerializer): | |
password2 = serializers.CharField() | |
class Meta: | |
model = VomUser | |
fields = ('id', 'email', 'sex', 'birthday', | |
'name', 'password', 'password2') | |
def __init__(self, *args, **kwargs): | |
# Don't pass the 'fields' arg up to the superclass | |
fields = kwargs.pop('fields', None) | |
# Instantiate the superclass normally | |
super(UserSerializer, self).__init__(*args, **kwargs) | |
if fields: | |
# Drop any fields that are not specified in the `fields` argument. | |
allowed = set(fields) | |
existing = set(self.fields.keys()) | |
for field_name in existing - allowed: | |
self.fields.pop(field_name) | |
@property | |
def data(self): | |
d = super(UserSerializer, self).data | |
if 'password' in d: | |
del d['password'] | |
return d | |
def restore_object(self, attrs, instance=None): | |
user = super(UserSerializer, self).restore_object(attrs, instance) | |
if instance is None: | |
user.set_password(attrs['password']) | |
return user | |
def to_native(self, obj): | |
if 'password2' in self.fields: | |
del self.fields['password2'] | |
return super(UserSerializer, self).to_native(obj) | |
def validate_sex(self, attrs, source): | |
if attrs['sex'] not in (0, 1): | |
raise serializers.ValidationError( | |
_("You must choice '1' or '0'. '1' means male and '0' means" + | |
" female. Your input: '%(value)s'"), | |
code='invalid', | |
params={'value': attrs['sex']} | |
) | |
return attrs | |
def validate_password2(self, attrs, source): | |
# http://goo.gl/U7FGWZ | |
if attrs['password'] == attrs.pop('password2'): | |
return attrs | |
raise serializers.ValidationError( | |
_("The two password fields didn't match."), | |
code='password_mismatch', | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment