'How to display Foreign key Data in Django view page?

i have relation between Project and ProjectFloorPlan, and i want to display ProjectFloorPlan data in my template. Please let me know how i can display the ForeignKey data in my template.

Here is my models.py file...

class Project(models.Model):
    name=models.CharField(max_length=225)
    slug=models.SlugField(null=True, unique=True)
   
    def __str__(self):
       return self.name


class ProjectFloorPlan(models.Model):
    project=models.ForeignKey('Project', related_name='projectfloorplan', on_delete=models.CASCADE, default=None)
    floorplan_image=models.ImageField(upload_to='floorplan_image')
    bhk=models.CharField(max_length=100)
    bed=models.CharField(max_length=100)
    created_at=models.DateTimeField(auto_now_add=True)
    updated_at=models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.project.name

here is my project.html file where i am trying o display ProjectFloorPlan data...but it's displaying nothing

{% fot i in project.projectfloorplan_set.all %}
<tr>
    <td>{{i.bhk}}</td>
    <td>{{i.bed}}</td>
    
</tr>
{% endfor %}


Solution 1:[1]

Since you have set related_name='projectfloorplan', you don't have to use _set notation to access the reverse FK.

So, use project.projectfloorplan.all instead of project.projectfloorplan_set.all

{% for i in project.projectfloorplan.all %}
<tr>
    <td>{{ i.bhk }}</td>
    <td>{{ i.bed }}</td>

</tr>
{% endfor %}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1