Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Display post to only user friends

When user login i want user to only see the post of friends with, I have a separate model for friends and a separate for post how do i filter post by users friends ?

Here is my view

def post_list(request):
    
    for user in Post.objects.all():
        if request.user.is_authenticated:
            friend_list = FriendList.objects.get(user=request.user )
            friends = friend_list.friends.all()
            context['friends'] = friends
 
  
    context['posts'] = Post.objects.prefetch_related('comments').filter(username=friends).order_by('-date_posted')
  
    return render(request,'feed/feed.html',context)    


Post model

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Post(models.Model):
    username = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    description = models.TextField(max_length=500, blank=True)
    date_posted = models.DateTimeField(auto_now_add=True)
    video = models.FileField(upload_to="videos",blank=True,null=True)
    tags = models.CharField(max_length=100, blank=True)
    views = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="view")
    shared_body = models.TextField(blank=True, null=True)
    shared_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, related_name='+')
    shared_on = models.DateTimeField(blank=True, null=True)

>Solution :

Try this

def post_list(request):
    
    context = {}
    if request.user.is_authenticated:
        friend_list = FriendList.objects.get(user=request.user )
        friends = friend_list.friends.all()
        context['friends'] = friends
        context['posts'] = Post.objects.filter(username__in=friends).order_by('-date_posted')
    return render(request,'feed/feed.html',context)

UPDATE
show current user posts and current user’s friends posts.

def post_list(request):
    
    context = {}
    if request.user.is_authenticated:
        friend_list = FriendList.objects.get(user=request.user )
        friends = friend_list.friends.all()
        context['friends'] = friends
        context['posts'] = Post.objects.filter(username__in=list(friends) + [request.user,]).order_by('-date_posted')
    return render(request,'feed/feed.html',context)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading