[Django]-How to get last login ip in django and save to a GenericIPAddressField?

8👍

For actually getting the user IP address you can utilise django-ipware. There are other methods but this app seems to cover as much as possible, you can check this question for the detailed information.

Once you have the USER_IP, you can create a middleware and update the last_ip for every request

# middleware.py
class LastLoginIP(object):
     def process_request(self, request):
         if request.user.is_authenticated():
            UserProfile.objects\
            .filter(user=request.user)\
            .update(last_ip=USER_IP)

# settings.py add the middleware
MIDDLEWARE_CLASSES = (
  ....
  your.middleware.LastLoginIP
)

Alternatively, if you already set up a system that only allows one concurrent login per profile (every time user switches devices, he/she has to login again) , then you can update the last_ip during the login.

Leave a comment