Home > OS >  Django render many to many in template
Django render many to many in template

Time:10-17

I have this models:

class roles(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=255, blank=False)
company = models.ForeignKey(Company, blank=True, null=True, on_delete=models.SET_NULL)

def __str__(self):
    return self.name

class freelancers(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
company = models.ForeignKey(Company, blank=True, null=True, on_delete=models.SET_NULL)
user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)
role = models.ManyToManyField(roles)

I try to get the name that is related to the user at the roles table.

In my view.py It looks like this:

def company_details(request,id):
obj = Company.objects.get(id=id)
pro = Projects.objects.filter(company=id)
free = freelancers.objects.filter(company=id)
#free = freelancers.objects.all()



return render(request, 'company/company_details.html',
{
    'obj':obj,
    'pro':pro,
    'free':free,
}
    )

And in the HTML:

{% for f in free %}
{{ f.user }} // <br/>
{% endfor %} 
{{ f.role.all }}
{% endfor %} 

I have been trying different ways to get the name to show up. Like: {{ f.role.name }}.

So any tips to make this work?

CodePudding user response:

I think you will have to iterate through the f.role.all

  • Related