Liked time of request.user is not showing

I just started learning Django. I am building a simple Blog App and I am trying to get the user liked time of post of request.user.

I made a Post model and a Like model. And when user like show the like time of user.

But it is not showing the liked time.

models.py

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=30, default='')

class Likepost(models.Model):
    by_user = models.ForeignKey(User, on_delete=models.CASCADE)
    post_of = models.ForeignKey(Post, on_delete=models.CASCADE)
    date_liked = models.DateTimeField(auto_now_add=True)

views.py

def blog_post_detail(request, post_id):
    obj = get_object_or_404(Post, pk=post_id)
    accessLikes = obj.likepost_set.all()

    for All in accessLikes:
        if request.user == All.by_user
            All.request.user.date_liked

    context = {'obj':obj}
    return render(request, 'blog_post_detail.html', context}

What i am trying to do :-

I am trying to access liked time of request.user

It is keep showing :-

Likepost’ object has no attribute ‘request’

I will really appreciate your help. Thank You

Answer

You can obtain the Likepost object of a user by filtering the queryset, and try to retrieve the corresponding like:

def blog_post_detail(request, post_id):
    obj = get_object_or_404(Post, pk=post_id)
    likepost = obj.likepost_set.filter(by_user=request.user).first()

    context = {'obj':obj, 'likepost': likepost}
    return render(request, 'blog_post_detail.html', context}

Next you can render this in the template with:

{% if likepost %}
    Liked by you at {{ likepost.date_liked }}
{% endif %}

Normally one can prevent multiple Likeposts for the same object and the same user with a UniqueConstraint [Django-doc]:

class Likepost(models.Model):
    by_user = models.ForeignKey(User, on_delete=models.CASCADE)
    post_of = models.ForeignKey(Post, on_delete=models.CASCADE)
    date_liked = models.DateTimeField(auto_now_add=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['by_user', 'post_of'],
                name='like_once_per_post'
            )
        ]

If you plan to store both like and unlike events, you get the most recent Likemodel with:

def blog_post_detail(request, post_id):
    obj = get_object_or_404(Post, pk=post_id)
    likepost = obj.likepost_set.filter(by_user=request.user).order_by('-date_liked').first()
    # …