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 inpost viewers
then show some text.
When i print {{ request.user.profile.friends.all }}
it show friends of request.user, It works correctly.
AND when i print {{ post.viewers.all }}
then it correctly shows the post viewers (users).
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.
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 %}