Django: Get IP Address using a signal

Question:

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

Asked By: wenbert

||

Answers:

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.

Answered By: S.Lott

As the instance is passed into the signal and the instance is really the same object that is saved, you can attach a request object or IP to the instance upon saving it.

user_login.request=request
user_login.save()

And retrieve it in the signal like

instance.request
Answered By: Frost.baka

Django has a signal that fires whenever a user logs in that is called user_logged_in. By attaching a signal handler to this signal you can be notified of login events. The handler is passed the user and request objects. As you note, you can get the IP address from the request object.

Answered By: Brian Neal

This is a very old question, but I had the same problem today and this was the first hit at Google. So maybe this helps other people as well. This is how it works for me.

from django.contrib.auth.signals import (
    user_logged_in,
    user_logged_out,
    user_login_failed,
)
from django.dispatch import receiver
import logging

user_logger = logging.getLogger("user")

@receiver(user_logged_in)
def log_user_login(sender, user, **kwargs):
    """log user "login" to log-file setup in django settings.py"""
    # if the IP-ADRESS is 127.0.0.1 from external users then check this     
    # https://stackoverflow.com/questions/4581789/how-do-i-get-user-ip-address-in-django
    request = kwargs["request"]
    ip_address = request.META.get("REMOTE_ADDR")
    user_logger.info(f"{user} login successful. IP-Address: {ip_address}")

# other functions deleted for brevity
Answered By: ChristianH
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.