0

I am creating a simple blog front end to consume a django backend api. The way it is setup so I can access user data for each post is like this:

post serializer:

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ['id', 'title', 'body', 'user']
        depth = 1

react, where i display the data

<Container variant='lg' maxWidth='lg'>
              <div className='posts'>
                <Typography key={post.id} variant='h3'>
                  {post.title}
                </Typography>
                <Typography paragraph>
                  {post.body}
                </Typography>
                <Typography paragraph>
                  {post.user.user_name}
                </Typography>
              </div>
</Container>

Now, this does fit as a solution to my problem, in order to have the users username be displayed in post, but it exposes all user data, including email, password hash, last logged in, etc.

What is better way to get user related data when using react?

2
  • Hi @stinny. That decision should not taken in the front-end. I think you should serialize the user data in the back end with django ( i have not used django). This is what I have done with rails. You just serialize the user data and in this way you avoid sensitive data of the user in your front-end Commented Jan 25, 2021 at 21:44
  • @JulioLopez ahhh that makes more sense. I will give that a try! Commented Jan 25, 2021 at 22:05

1 Answer 1

1

Modify your serializer as follows. Instead of using depth get user name as follows

class PostSerializer(serializers.ModelSerializer):
    #use Serializer method fields
    user_name = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = ['id', 'title', 'body', 'user_name']

    def get_user_name(self, obj):
        try:
            return obj.user.user_name
        except:
            pass

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

Comments

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.