# encoding:utf-8
import logging
from django.contrib.auth.models import User
from rest_framework import serializers
from account.models import UserProfile
from cmmedia.serializers import ImageSerializer

log = logging.getLogger('root')

__author__ = 'quxl'


class UserSerializer(serializers.ModelSerializer):
    """
    User register serizlizer
    """
    password = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ('username', 'password')

    def create(self, validated_data):
        user = User.objects.create_user(username=validated_data['username'], password=validated_data['password'])
        self.generate_profile(user)
        return user

    def generate_profile(self, user):
        profile = UserProfile(user=user)
        profile.save()


class UserProfileSerializer(serializers.ModelSerializer):
    head_photo = ImageSerializer()

    class Meta:
        model = UserProfile
        fields = ('first_name', 'introduction', 'gender', 'birthday', 'region', 'head_photo',)

    def update(self, instance, validated_data):
        """
        update user profile
        :param instance: the instance of UserProfile
        :param validated_data: the date , client update
        :return: UserProfile instance
        """
        hp = validated_data.pop('head_photo')
        profile = super(UserProfileSerializer,self).update(instance,validated_data)

        head_photo = profile.head_photo
        head_photo.file = hp['file']
        head_photo.save()
        return profile


@@ -147,16 +147,49 @@
 Profile%0A
+from cmmedia.models import Image%0A
 from cmm
@@ -1401,16 +1401,17 @@
 ializer,
+ 
 self).up
@@ -1424,16 +1424,17 @@
 nstance,
+ 
 validate
@@ -1445,49 +1445,377 @@
 ta)%0A
-%0A        head_photo = profile.head_photo%0A
+        self.update_or_create_head_photo(profile, hp)%0A        return profile%0A%0A%0A    def update_or_create_head_photo(self, profile, hp):%0A        head_photo = profile.head_photo%0A        if not head_photo:%0A            head_photo = Image(file=hp%5B'file'%5D)%0A            head_photo.save()%0A            profile.head_photo = head_photo%0A            profile.save()%0A        else:%0A    
     
@@ -1847,16 +1847,20 @@
 'file'%5D%0A
+    
         

update userprofile bug,