Lars
Lars

Reputation: 1270

ManyToMany fields are not showing in if statement in template

I am building a BlogApp and I am stuck on a Problem.

What i am trying to do :-

I am trying to use if statement in template of two many fields BUT if statement is not working correctly.

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True)
    friends = models.ManyToManyField("Profile",blank=True)

class Post(models.Model):
    post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE)
    viewers = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='viewed_posts',editable=False)

views.py

def detail_view(request,pk,slug):
    post = get_object_or_404(Post,pk=pk)

    friend = request.user.profile.friends.all()
    saw = post.viewers.all()

    context = {'friend':friend,'saw':saw}

template.html

{% if request.user.profile.friends.all in post.viewers.all %}

"SHOWING SOME TEXT"

{% endif %}

I am trying to show if request.user friends are in post viewers then show some text.

When i try to print some text after combine both in if statement then it doesn't showing anything.

I have no idea where is the Mistake.

Any help would be Appreciated.

Thank You in Advance.

Upvotes: 1

Views: 139

Answers (2)

NKSM
NKSM

Reputation: 5854

You can filter in the view:

def detail_view(request,pk,slug):
    post = get_object_or_404(Post,pk=pk)

    friend = request.user.profile.friends.all()
    saw = post.viewers.all()

    seen_friends = post.viewers.filter(
        id__in=friend.values_list("user_id")
    ).exists()

    context = {
        'friend':friend,'saw':saw, 
        'seen_friends':seen_friends
    }

in template.html:

{% if seen_friends %}

"SHOWING SOME TEXT"

{% endif %}

Upvotes: 1

alv2017
alv2017

Reputation: 860

The problem is in this line

{% if request.user.profile.friends.all in post.viewers.all %}

Update:

The template has an access to request.user object, but not to the profile object. You are trying to apply Django ORM methods in the template, it is not going to work.

def detail_view(request,pk,slug):
    # some code
    profile = Profile.objects.get(user=request.user)
    context = {'profile':profile}
    # more code
    return render(request, template_file, context)

Upvotes: 0

Related Questions