1

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.

1 Answer 1

1

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)}

Sign up to request clarification or add additional context in comments.

5 Comments

But request.user.user_profile doesnt exist. ryt? then how will it work ?
ok so i made a UserProfile model and passed it into serializer and it worked......, but isnt this supposed to do it automatically, i mean something like: i should pass the user model into the UserProfileSerializer and it should find the the corresponding user, assign it itself and return the serialized UserProfile model ........
It would work if you would do this in the opposite way. Return a User serializer that would include the user profile serializer too. Please check the nested serializers documentation: django-rest-framework.org/api-guide/relations/…
But that would mean in User model, there should be an added field,.... ryt ?...... Bcoz....... according to what i know......... in fields of serializers, only the attributes in the model can be added.
You can do the same thing in the User serializer that you did in the UserProfile serializer: class UserSerializer(serializers.ModelSerializer): ` user_profile = UserProfileSerializer()` Please read about reverse relations in django to understand how this work:docs.djangoproject.com/en/1.8/topics/db/examples/one_to_one As you can see in the example you can do things like: p1.restaurant even if you don't have a foreign key to Restaurant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.