问题
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