访问模板中的多个到多个数据

时间:2013-04-26 13:23:11

标签: django django-templates

我有两个模型,一个在多对多关系中引用另一个模型(BannerProject对象可能包含BannerEntry对象的多个实例):

class BannerEntry(models.Model):
    title = models.CharField(max_length=100, unique=False, blank=False, null=False)
    has_static = models.BooleanField()
    has_flash = models.BooleanField()
    static_preview = models.FileField(upload_to=content_banner_page, blank=True, null=True, max_length=300)
    static_zip = models.FileField(upload_to=content_banner_page, blank=True, null=True, max_length=300)
    ...

class BannerProject(models.Model):
    client = models.CharField(max_length=50, choices=CLIENT_CHOICES)
    project_name = models.CharField(max_length=100, unique=False, blank=False, null=False)
    parent_page = models.ForeignKey(BannerPage, blank=True, null=True)
    banner_entry = models.ManyToManyField(BannerEntry)

    def __unicode__ (self):
            return u'%s %s' % (self.client, self.project_name)

    class Admin: 
            pass

运行基本视图功能:

def display_bannerpage(request, client):
    records = BannerPage.objects.filter(client=client)
    bprjrecords = BannerProject.objects.filter(client=client)
    tpl = 'clientportal_tmps/bannerpage.html'
    return render_to_response(tpl, { 'records': records, 'bprjrecords': bprjrecords })

我希望在模板中显示它们(BannerProject,子Entry1字段,childEntry2字段,子Entry3字段......下一个BannerProject等...): 我当前的模板看起来像:

{% if bprjrecords %}
{% for bprjrecord in bprjrecords %}

{% for banner_entry in bprjrecord %}
{{ banner_entry.title }}
{{ banner_entry.static_preview }}
{{ banner_entry.static_zip }}
{% endfor %}

抛出TypeError“'BannerProject'对象不可迭代”

什么是允许我访问BannerEntry数据的正确模板语言,以便我可以在模板中显示它?

1 个答案:

答案 0 :(得分:0)

您正在尝试迭代BannerProject,而不是该项目的BannerEntry列表。试试这个:

{% for banner_entry in bprjrecord.banner_entry.all %}
    {{ banner_entry.title }}
    {{ banner_entry.static_preview }}
    {{ banner_entry.static_zip }}
{% endfor %}