How to check whether a user is online in django template?

后端 未结 6 1050
终归单人心
终归单人心 2020-12-05 09:16

In template, when I use

{% if topic.creator.is_authenticated %}
Online
{% else %}
Offline
{% endif %}

the users turn out to be always onli

6条回答
  •  一个人的身影
    2020-12-05 09:24

    As the documentation says:

    Even though normally you will check is_autheticated attribute on request.user to find out whether it has been populated by the AuthenticationMiddleware (representing the currently logged-in user), you should know this attribute is True for any User instance.

    So to check if user is online I would do something like this:

    models.py

    class Profile(models.Model):
        user = models.OneToOneField(User, related_name='profile')           
        is_online = models.BooleanField(default=False)
    

    views.py

    from django.contrib.auth.signals import user_logged_in, user_logged_out
    from django.dispatch import receiver    
    
    @receiver(user_logged_in)
    def got_online(sender, user, request, **kwargs):    
        user.profile.is_online = True
        user.profile.save()
    
    @receiver(user_logged_out)
    def got_offline(sender, user, request, **kwargs):   
        user.profile.is_online = False
        user.profile.save()
    

    And then in your template you would check if user is online:

    {% if user.profile.is_online %}
        Online
    {% else %}
        Offline
    {% endif %}
    

    Don't forget to return user instance to your template in order for user.profile.is_online to work.

提交回复
热议问题