F4z F4z - 1 year ago 126
Python Question

Passing Django Model to Template

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

model which holds information on a certain project and then have another model called
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

So far my
is as below:

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

Problem is in my
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:

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)

Answer Source

Inside your template projects.html you should be able to loop over the Links for each project with

{% for project in projects %}
  {% for link in project.link_set.all %}
      {{ link }}
  {% endfor %}
{% endfor %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download