dreamer
dreamer

Reputation: 901

How to implement serializing for nested objects

Had implemented a basic authentication system using function based views in django.

Trying to upgrade it to class based views.

Creating a UserProfile by inheriting from a django User model.

Need to serialize UserProfile and return to client side

User model :

from django.contrib.auth.models import User

UserProfile model :

class UserProfile(models.Model):
id = models.AutoField(primary_key=True)
user = models.OneToOneField(User)
profile_picture = models.ImageField(upload_to='documents', blank=True)

def __str__(self):
    return self.user.username

UserSerializer:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username','password', 'first_name', 'last_name', 'email',)
        write_only_fields = ('password',)
        read_only_fields = ('is_staff', 'is_superuser', 'is_active', 'date_joined',)

        def restore_object(self, attrs, instance=None):
            user = super(UserSerializer, self).restore_object(attrs, instance)
            user.set_password(attrs['password'])
            return user

UserProfileSerializer:

class UserProfileSerializer(serializers.ModelSerializer):
    user = UserSerializer()
    class Meta:
        model = UserProfile
        fields = ('id','user','profile_picture',)

views.py:

class AuthView(APIView):
    authentication_classes = (BasicAuthentication,)
    def post(self, request, *args, **kwargs):
        login(request, request.user)
        content={ 'user':UserProfileSerializer(request.user).data,'token':csrf.get_token(request)}
        return Response(content)  

UserProfileSerializer(request.user).data in views.py is not working. but instead if i use: UserSerializer(request.user).data, it gives me result(as expected) :

{'first_name': '', 'username': 'admin', 'email': '[email protected]', 'last_name': '', 'password': 'pbkdf2_'}

But i also want additional attributes to the user also serialized like profile_picture, hence something like

UserProfileSerializer(request.user).data

should work for me.

Questions:

  1. Is it possible to serialize a model containing FileField ?

  2. How to serialize a nested object and return its data ?

Kinda beginner here.

Upvotes: 1

Views: 484

Answers (1)

norbert.mate
norbert.mate

Reputation: 302

yes it is possible to serialize a FileField. The problem is that your profile serializer needs a UserProfile model and not a User model. Try this:

content={ 'user':UserProfileSerializer(request.user.user_profile).data,'token':csrf.get_token(request)}

Upvotes: 1

Related Questions