Issue
If you have a better way to reformulate my question please let me know. My template is as follows:
{% for x in group.groupmember_set.all %}
{% if x.user != user.username %}
{{ x.user }}
{% endif %}
{% endfor %}
This statement prints all users in the Group, as though the if statement doesn't exist. If I remove the if statement, eventually prints the same and makes sense... I want to filter out user.username
with an if statement but doesn't work. What is wrong? Group has a ManytoMany relation with User through GroupMember.
My models.py
file reads:
class Group(models.Model):
name = models.CharField(max_length=255, unique=True)
members = models.ManyToManyField(User,through="GroupMember")
class GroupMember(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE,)
group = models.ForeignKey(Group,on_delete=models.CASCADE,)
is_valid = models.BooleanField(default=False)
and in views.py
I use DetailView
, e.g.,
class SingleGroup(DetailView):
model = Group
Solution
If you haven't set user
variable in template nor passed it in view's context, then you should use request.user
. Change it like that:
{% for x in group.groupmember_set.all %}
{% if x.user != request.user %}
{{ x.user }}
{% endif %}
{% endfor %}
Another thing is you should compare object of the same type, ie. User
object to User
object or username
string to username
string - definitely not User
object to username
string.
Answered By - NixonSparrow
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.