在 django 模板中渲染 ManytoManyfield 而不复制父模型的内容

Posted

技术标签:

【中文标题】在 django 模板中渲染 ManytoManyfield 而不复制父模型的内容【英文标题】:Render ManytoManyfield in django templates without duplicating the content of the parent Model 【发布时间】: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 感谢您的帮助!我想我什么都试过了,除了考虑如何渲染它。 【参考方案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 %

【讨论】:

以上是关于在 django 模板中渲染 ManytoManyfield 而不复制父模型的内容的主要内容,如果未能解决你的问题,请参考以下文章

django ManyToMany 模型视图和模板

django DetailView 没有从 ManyToMany 字段中捕获数据

如何在 Django 模板中的“带有模板标签”中设置 Django 渲染块值?

通过 Django 模板中的视图传递变量

Django模板渲染

渲染后如何获取模板(Django)