I am trying to log the IP address of the user that is trying to login using signals. How do I do this?
I have already captured the datetime for the login.
#models.py
class UserLogin(models.Model):
"""user details when logging in"""
user = models.ForeignKey(User)
timestamp = models.DateTimeField(auto_now=True)
This is for the signal:
#models.py
def user_login_save(sender, instance, **kwargs):
if instance.last_login:
old = instance.__class__.objects.get(pk=instance.pk)
if instance.last_login != old.last_login:
instance.userlogin_set.create(timestamp=instance.last_login)
models.signals.post_save.connect(user_login_save, sender=User)
Although I know how to get the IP Address using: request.META[REMOTE_ADDR] my problem is that I cannot use the request instance in my model. I am not also sure if getting something from the request is good practice.
What is the recommended way of doing this?
Any reply will be greatly appreciated.
Regards, Wenbert
Although I know how to get the IP Address using: request.META[REMOTE_ADDR] my problem is that I cannot use the request instance in my model.
That's why you have view functions.
I am not also sure if getting something from the request is good practice.
It is perfectly fine.
That's why the request is provided to every view function.
That's why you have view functions.
Just do it in the view function. Don't mess with signals unless you're writing a new kind of database interface.