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

How to display data from many to many field to a tempate

我的问题类似于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 地址列表

在第二个 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 %}