如何将多个到多个字段的数据显示到模板

时间:2015-01-07 17:05:39

标签: python django django-orm

我的问题类似于Question on Django: Displaying many to many fields

给出的答案对我帮助不大!

models.py

class MacAddress(models.Model):
      address = models.CharField(max_length = 20,null=True,blank=True)
      def __unicode__(self):
         return self.address

class UserProfile(models.Model):
    user = models.OneToOneField(User,primary_key=True,db_index=True)
    MAC=models.ManyToManyField(MacAddress,related_name='macAddress')
    def __unicode__(self):
        return self.user.username

views.py

def mac(request):
    context = RequestContext(request)
    entries = UserProfile.objects.all()
    e = {'posts' : entries }
    return render_to_response('t.html',e, context)

t.html

{% for post in posts %}
{%  for p in posts.MAC.all %}
{{ p }}
{% endfor %}{% endfor %}

如何在t.html中显示与用户对应的mac地址列表

1 个答案:

答案 0 :(得分:2)

在第二个for循环中,你应该写post.MAC.all。现在你正在写posts.MAC.all,这会给你错误的结果。

{% for post in posts %}
{%  for p in post.MAC.all %} # You should write post.MAC.all instead posts.MAC.all
{{ p }}
{% endfor %}{% endfor %}