How to save the users last logout time

爷,独闯天下 提交于 2019-12-24 21:24:58

问题


I am looking to save the users last logout time.My idea was to add it to the users profile model. I am using Django 1.11.15

Example:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE) 
    ...
    last_logout = models.DateTimeField(blank=True, null=True) 

below is how I created my profile model just for reference

def signup(request):
    if request.method == 'POST':
        form = UserCreateForm(request.POST or None)
        if form.is_valid():
            new_user = form.save()
            Profile.objects.create(user=new_user)
            return redirect('accounts:edit_profile')
    else:
        form = UserCreateForm()
    context = {'form': form}
    return render(request, 'accounts/signup.html', context)

Below is what I intend to do. Is this the correct way. I want to add to django's default signout/logout method I am not sure if its called signout or logout

class LoggedOut(TemplateView):
    template_name = 'logged_out.html'
    def signout(self):
        """logout user """
        self.request.user.profile.last_logout = datetime.now()
        self.request.user.profile.save()

My URL's

url(r'^loggedout/$', views.LoggedOut.as_view(), name='loggedout'),

回答1:


You can use Django logout signal for such purpose.

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

@receiver(user_logged_out)
def sig_user_logged_out(sender, user, request, **kwargs):
     user.profile.last_logout = datetime.now()
     user.profile.save()


来源:https://stackoverflow.com/questions/53837536/how-to-save-the-users-last-logout-time

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