How to Access Current User from Django to React?

Viewed 3430

I am developing a system where a user logs in and they can use the features of our service. We have used Django Authentication to make the User and Login backend. This is the custom User model in my models.py -

class UserDef(AbstractUser):
    def __str__(self):
        return self.first_name + self.last_name
    
    employeeId = models.IntegerField(unique=True)
    email_address = models.EmailField()
    first_name = models.CharField(max_length=256)
    last_name = models.CharField(max_length=256)
    USER_TYPES = [('1',"Admin"), ('2',"Director"), ('3',"Sr. Manager"), ('4',"Manager") , ('5',"Sr. Engineer"), ('6',"Assistant Regional Manager"), ('7',"Assistant to the Regional Manager")]
    user_type = models.CharField(max_length=2048, choices=USER_TYPES)
    created_at = models.DateTimeField(auto_now_add=True)

This in itself works really well and I was able to access all data as needed. I am writing my front-end in React though. Which means there's a certain disconnect between the templates html file and the actual React.js code. Which means I can't simply send the employeeId or some other attribute as context. Does anyone know how I can extract that User information from the Django DB (which we have connected to an RDS-MySQL server) and display it in my React app.

1 Answers

If the user is already logged in and a sessionID has been generated. You could just create an endpoint through where you can fetch the current user and then make a call to the endpoint in your React frontend.

@api_view(['GET'])
def current_user(request):
    user = request.user
    return Response({
      'username' : user.username,
      'firstname' : user.first_name,
      'employeeID' : user.employeeId,
       # and so on...
    })

You could obviously, always use a serializer to ease the process.

Related