SHARE
TWEET

Untitled

a guest Jun 7th, 2017 122 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from rest_framework import serializers
  2.  
  3. from users.models import User
  4.  
  5.  
  6. class UserSerializer(serializers.HyperlinkedModelSerializer):
  7.     todos = serializers.HyperlinkedRelatedField(
  8.         many=True,
  9.         view_name='todos:todo-detail',
  10.         read_only=True
  11.     )
  12.     password = serializers.CharField(write_only=True)
  13.  
  14.     def create(self, validated_data):
  15.         user = User(
  16.             username=validated_data.get('username', None)
  17.         )
  18.         user.set_password(validated_data.get('password', None))
  19.         user.save()
  20.         return user
  21.  
  22.     def update(self, instance, validated_data):
  23.         for field in validated_data:
  24.             if field == 'password':
  25.                 instance.set_password(validated_data.get(field))
  26.             else:
  27.                 instance.__setattr__(field, validated_data.get(field))
  28.         instance.save()
  29.         return instance
  30.  
  31.     class Meta:
  32.         model = User
  33.         fields = ('url', 'id', 'username',
  34.                   'password', 'first_name', 'last_name',
  35.                   'email', 'todos'
  36.                   )
  37.         extra_kwargs = {
  38.             'url': {
  39.                 'view_name': 'users:user-detail',
  40.             }
  41.         }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top