【问题标题】:Render ManytoManyfield in django templates without duplicating the content of the parent Model在 django 模板中渲染 ManytoManyfield 而不复制父模型的内容
【发布时间】:2014-04-29 10:00:14
【问题描述】:

我在这方面有很大的困难。

我正在尝试如下呈现我的模板:

公司名称A:

-> 邮政编码 1

-> 邮政编码 2

我现在有这个结果:

公司名称A:

-> 邮政编码 1

公司名称A:

-> 邮政编码 2

我知道它来自我在 cp 上的 for 循环,但我不知道如何访问 M2M 字段以按我的意愿显示它。 (而且我还有一个额外的 m2m 字段,所以这将是另一个 for 循环)

这是我的代码:

models.py

class Company(models.Model):
    utilisateur = models.ForeignKey(User)
    nom_cpny = models.CharField(max_length=200)
    code_postal_cpny = models.ManyToManyField('Place', blank=True)
    gestion_cpny = models.ManyToManyField('Companytype', blank=True)

    def __unicode__(self):
            return self.nom_cpny


class Place(models.Model):
    postalcode = models.CharField(max_length=200)
    ville = models.CharField(max_length=200)
    region = models.CharField(max_length=200)
    departement = models.CharField(max_length=200)
    longitude = models.DecimalField(max_digits=9, decimal_places=6)
    latitude = models.DecimalField(max_digits=9, decimal_places=6)
    pays = models.CharField(max_length=100)

    def __unicode__(self):
        return unicode(self.postalcode)


class Companytype(models.Model):

    cpny_type = models.CharField(max_length=100, blank=False) 
    employee_base = models.IntegerField(blank=False)

    def __unicode__(self):
        return self.cpny_type

views.py

@login_required
def listing_cpny(request):

    cpny_in = Company.objects.all().filter(utilisateur=request.user)
    utilisateur = request.user    

    args = {}
    args.update(csrf(request))

    args['cpny_in'] = cpny_in
    args['utilisateur'] = utilisateur

    return render_to_response('b_dashboard_annonces.html', args) views.py

b_dashboard_annonces.html

{% for annonce in cpny_in %}
    {% for cp in annonce.code_postal_cpny.all %}
    {% if annonce.utilisateur.id == utilisateur.id %}


    <td>{{annonce.nom_cpny}}</td>
    <td>{{cp }}</td>


    </tr>
    {% endif %}
    {% endfor %}
{% endfor %}

非常感谢您的帮助!

【问题讨论】:

  • @blobmarket 感谢您的帮助!我想我什么都试过了,除了考虑如何渲染它。

标签: python django django-models django-templates django-orm


【解决方案1】:

这应该适合你

{% for annonce in cpny_in %}
    <tr>
        <td>{{annonce.nom_cpny}}</td>

        {% for cp in annonce.code_postal_cpny.all %}
            {% if annonce.utilisateur.id == utilisateur.id %}
                <td>{{cp }}</td>
            {% endif %}
        {% endfor %}

    </tr>
{% endfor %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 2022-07-22
    • 2014-03-10
    • 2013-08-29
    • 1970-01-01
    相关资源
    最近更新 更多