3

I'm extending the user profile and added a last_ip field as shown below. How do I update this field whenever a user is logged in to its current IP? I am using allauth if it matters.

class UserProfile(models.Model):  
    user = models.OneToOneField(User)
    last_ip = models.GenericIPAddressField(protocol='IPv4', verbose_name="Last Login IP")
    location = models.CharField(max_length=50, blank=True)
bayman
  • 1,579
  • 5
  • 23
  • 46

1 Answers1

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.

Community
  • 1
  • 1
Tiny Instance
  • 2,351
  • 17
  • 21
  • Ensure the module path of the new middleware `LastLoginIP` is placed after `django.contrib.auth.middleware.AuthenticationMiddleware` in `MIDDLEWARE_CLASSES`, the attribute `user` is added to `request` only after running `AuthenticationMiddleware.process_request()` – Ham Nov 24 '20 at 16:24