I'm looping through the field of joined
for my Group model and returning the list of joined members in my GroupDetail template:
class Group(models.Model):
leader = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=55)
description = models.TextField()
joined = models.ManyToManyField(User, blank=True)
Each member in the for loop relates to a User (or username) that has joined the Group:
<ul>
{% for member in joined_members %}
<li>{{ member }}<li>
{% endfor %}
</ul>
There are four members in the Group, and all members are being returned, however four empty list items are also being returned as such (via chrome dev tools):
<ul style="display: block;">
<li>joe</li>
<li></li>
<li>johnny</li>
<li></li>
<li>ralph</li>
<li>/li>
<li>mike</li>
<li></li>
</ul>
There are only four members (Users) joined to this particular group, so I don't understand what's happening. I assume the issue is from how I passed the data into the template from my view:
class GroupDetail(DetailView):
model = Group
template_name = 'group_details.html'
def get_context_data(self, *args, **kwargs):
group = get_object_or_404(Group, id=self.kwargs['pk'])
joined_members = group.joined.all()
context = super(GroupDetail, self).get_context_data()
context["joined_members"] = joined_members
return context
There are no actual errors, just these four empty list items. Is the issue with my for loop? Or is it with how I'm passing my context?
CodePudding user response:
I think you understand via this Example. You can write your context like this
def index(request):
post = Post.objects.all()
context = {'post':post}
return render(request, 'blog/bloghome.html', context)
In your Template
<ul>
{% for i in post %}
<li>{{ i.title }}<li>
{% endfor %}
</ul>
I think now you can understand
CodePudding user response:
changing my list to:
<ul>
{% for member in group.joined.all %}
<li>{{ member }}<li>
{% endfor %}
</ul>
Solved the issue for me. I was able to delete the lines passing joined_members
as well, but I'm not sure exactly how this solved my issue. But it did.