【问题标题】:django display in htmldjango在html中显示
【发布时间】:2016-08-24 08:59:24
【问题描述】:

我的模型中有两个类:

class FicheFormation(models.Model):
    intitule=models.TextField(blank=False,null=False)
    duree=models.IntegerField(blank=False,null=False)
    objective=models.TextField(blank=False,null=False)
    niveau=models.TextField(blank=False,null=False)
    prix=models.IntegerField(blank=False,null=False)
    comptecf=models.ForeignKey('CompteRF',related_name='fichecompte',null=False)
    unite= models.ManyToManyField('UniteFormation', related_name='unitefiche')

class UniteFormation(models.Model):
    nomUe=models.TextField(blank=False,null=False)
    acronyme=models.TextField(blank=False,null=False)
    commentaire=models.TextField(blank=True,null=True)

我想显示一个comptecf的编队列表,

所以我在我看来这个方法:

def getFormation(request):
 #   user = request.user
 #   if user and user.is_active:
 #   u=user.username
    c=CompteRF.objects.all().filter(username='Me')
    queryset=FicheFormation.objects.all().filter(comptecf=c)
    return render_to_response('formation.html', {'formations':queryset},
                                  context_instance=RequestContext(request))

在我的formations.html中:

% for car in formations %}
            <tr>
                <td>{{ car.intitule}}</td>
                <td>{{ car.objective }}</td>
                <td>{{ car.unite }}</td>
            </tr>
{% endfor %}

更新:

{% for car in formations %}
            <tr>
                <td>{{ car.intitule}}</td>
                <td>{{ car.objective }}</td>
        % for car in formations %}
                <td>{{ car.unite.nomUe }}</td>
        {% endfor %}
            </tr>
{% endfor %}

它适用于 =car.intitule 和 car.objective 但对于 car.unite 它显示无,我不明白为什么因为它在控制台中通常显示联合“Sarra”,我需要做:c=unite。 all(),然后是 c[0].nomUe,它可以工作并附加“Sara”,但在我看来或 html 中,当我尝试在 car.unite 上进行迭代时,我收到了一条错误消息!

【问题讨论】:

  • 什么错误信息?你如何迭代car.unite
  • 我做到了:% 用于编队 %} {{ car​​.intitule}} {{ car​​.objective }} %对于编队中的汽车 %} {{ car​​.unite.nomUe }} {% endfor %} {% endfor %}
  • 请将其作为问题的更新,格式正确。您似乎迭代了两次formations,而不是unite
  • 好吧unite 是多对多关系,那么它应该显示(可能的)哪一个?
  • 它应该显示许多 UniteFormation

标签: django django-models django-views django-template-filters


【解决方案1】:

要遍历相关的unite 对象,您需要遍历car.unite.all()。在模板中,您删除了括号,因此您可以执行以下操作:

<td>{% for unite in car.unite.all %}{{ unite.nomUe }}{% endfor %}</td>

【讨论】:

    猜你喜欢
    • 2015-04-15
    • 1970-01-01
    • 2015-07-31
    • 2019-08-11
    • 2020-03-19
    • 2013-04-20
    • 1970-01-01
    • 2015-05-09
    • 1970-01-01
    相关资源
    最近更新 更多