Passing Django Model to Template
<p>I have a little problem which I can't seem to get my head around. It seems like a very trivial thing but I just can't figure it out. Essentially what I'm trying to do is to create a <code>Project</code> model which holds information on a certain project and then have another model called <code>Link</code> which holds the name of the link such as 'Get Program' or 'Download Release' and have a URLField which holds the URL for those links and is child of <code>Project</code>.</p>

<p>So far my <code>models.py</code> is as below:</p>

<pre><code>from django.db import models

class Project(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()

    def get_name(self):
        return self.name

    def get_description(self):
        return self.description

    def __str__(self):
        return self.name

class Link(models.Model):
    project = models.ForeignKey(Project)
    name = models.CharField(max_length=255)
    url = models.URLField()

    def get_name(self):
        return self.name

    def __str__(self):
        return self.name
</code></pre>

<p>Problem is in my <code>views.py</code> I want to be able to pass Projects object so I can iterate over them and display all links for each project including the project objects fields such as name and description. So far I've done:</p>

<pre><code>from django.shortcuts import render
from django.http import HttpResponse
from .models import Project, Link

def projects_index(request):

    projects = Project.objects.all()
    links = Link.objects.all()

    context = {
        'projects': projects,
    }
    return render(request, 'projects.html', context)
</code></pre>

<p>You really should do the tutorial. </p>

<pre><code>for project in projects:
    for link in project.link_set.all:
        &lt;...&gt;
</code></pre>

<p>Add a <code>related_name="links"</code> to your foreign key, and the inner loop can be</p>

<pre><code>for link in project.links:
</code></pre>

python django django-models