Skip to content Skip to sidebar Skip to footer

Django Created_at__gt=self.request.user.last_login Workinly Only On Users Already Signed In.

Intro: I have a 3 models user, post, group. User is able to make posts however each post has to belong to a group. Users have to choose from the existing groups for their posts. Us

Solution 1:

Well, its normal behavior because last_login stores datetime at which the user last logged in. When the user fresh logs in into the system, it stores the current time (timezone.now). So if a post is created before he is logged in, then it will not appear into the new_posts. So if you want to store the previous login/logout time, then you need to store it somewhere else(or make a new model field). You can try like this using user logged out signal:

from django.contrib.auth.signals import user_logged_out


def do_stuff(sender, user, request, **kwargs):
    user.logout_time = timezone.now()
    user.save()

user_logged_out.connect(do_stuff)  # Hook an a method to user_logged_out signal to update logout time

And use it in the View like this:

last_post = Post.objects.last()
if last_post.created_at < request.user.last_login:
   new_posts = Post.objects.filter(created_at__gt=self.request.user.logout_time).count()
   context['new_posts'] = new_posts

Update

In this example, it is required to have a field to store logout time. If you have a CustomUser then you can directly create it in the CustomUser Model. Else, you can add it like this:

class Profile(models.Model):
    user = models.OneToOneField(User)
    logout_time = models.DateTimeField(default=timezone.now)

and store logout time like this:

user.profile.logout_time = timezone.now()

and filter New Posts Like this:

new_posts = Post.objects.filter(created_at__gt=self.request.user.profile.logout_time)

Post a Comment for "Django Created_at__gt=self.request.user.last_login Workinly Only On Users Already Signed In."