How to add the last_login_ip, when the user login if using `rest-auth`?

久未见 提交于 2019-12-24 16:40:46

问题


How to add the last_login_ip, when the user login if using rest-auth?

Befor ask the post I searched one post bellow:

How can I do my logic in `http://127.0.0.1:8000/rest-auth/login/` of `django-rest-auth`?

The answer is perfect for custom verify the login params.

But, how about after login, then add attribute to the User?

I mean, the answer is just for verify the data, I want to after user login success, I want to add the last_login_ip to the user instance.


EDIT

Please be attention, I know how to get the remote IP who visit my site. I mean I use the rest-auth to login, and customized LoginSerializer like the link. The link is for verify the login data, I can not to change the last_login_ip data in the LoginSerializer, I want when the user login success, then change the user's last_login_ip. but where to write my change last_login_ip code?


EDIT-2

I follow the @at14's advice, in the init.py (as the same level as apps.py):

default_app_config = '管理员后台.用户管理.qiyun_admin_usermanage.apps.QiyunAdminUsermanageConfig'

and in the apps.py:

from django.apps import AppConfig

class QiyunAdminUsermanageConfig(AppConfig):
    name = 'qiyun_admin_usermanage'

    def ready(self):
        import 管理员后台.用户管理.qiyun_admin_usermanage.api.signals

There will get bellow error:

django.core.exceptions.ImproperlyConfigured: Cannot import 'qiyun_admin_usermanage'. Check that '管理员后台.用户管理.qiyun_admin_usermanage.apps.QiyunAdminUsermanageConfig.name' is correct.

and I also tried to comment the default_app_config = '管理员后台.用户管理.qiyun_admin_usermanage.apps.QiyunAdminUsermanageConfig' in the init.py, but still not work.


回答1:


Use django's user logged in signal to save this information into the database.

In signals.py,

from django.contrib.auth.signals import user_logged_in
from django.dispatch import receiver

@receiver(user_logged_in)
def user_logged_in_callback(sender, user, request, **kwargs):
   // Get the IP Address and save it

Read more about signals here. Do pay attention on how to import signals in your app ready method

Make an apps.py (it might already exist) in your app directory,

from django.apps import AppConfig


class YourAppConfig(AppConfig):
    name = '管理员后台.用户管理.qiyun_admin_usermanage'

    def ready(self):
        import 管理员后台.用户管理.qiyun_admin_usermanage.api.signals  # noqa

In your apps init.py file,

default_app_config = '管理员后台.用户管理.qiyun_admin_usermanage.apps.QiyunAdminUsermanageConfig'


来源:https://stackoverflow.com/questions/48257161/how-to-add-the-last-login-ip-when-the-user-login-if-using-rest-auth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!