在模板中获取ManyToMany字段值

时间:2012-02-06 07:43:47

标签: python django django-templates many-to-many

我在模板中获取ManyToMany字段值时遇到问题,这是代码:

models.py

class Client(models.Model):
name = models.CharField(max_length=18,help_text='Nazwa firmy klienta, musi być unikalna', verbose_name='Klienci')
slug = models.SlugField(max_length=255,help_text="Wartość sugerowana automatycznie na podstawie nazwy", unique=True, verbose_name='Odnośnik')
iconwhite =  models.ImageField(upload_to='iconswhite', verbose_name='ikona na białym tle', blank=True)
class Meta:
    ordering = ['name']
    verbose_name = "Klient"
def __str__(self):
    return self.name
def __unicode__(self):
    return self.name
def get_absolute_url(self):
    return '/clients/%s/' % self.slug

models.py

class Projects(models.Model):
def get_picture_path(instance, filename):
    return os.path.join('picture', str(instance.id), filename)
client = models.ManyToManyField(Client, verbose_name='Klient')
title = models.CharField(max_length=255, verbose_name='Tytuł projektu')
slug = models.SlugField(max_length=255, unique=True, verbose_name='Odnośnik')
status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='d')
picture = models.ImageField(upload_to=get_picture_path, blank=True, null=True, help_text='Miniatura widoczna na str głównej oraz w galerii projektow')
class Meta:
    verbose_name = "Projekt"
def __str__(self):
    return self.title
def __unicode__(self):
    return self.title
def get_absolute_url(self):
    return '/projects/' + self.slug + '/' 

的index.html

<div class="grid_4">
    <div class="container_img">
        <div><a href="/projects/{{ i.slug }}/"><img src="site_media/media/{{i.picture}}" /></a></div>
        <div class="client_icon">
        {% for client in projects.client.all %}
        <img src="site_media/media/{{client.iconwhite}}" />
        {% endfor %}
        </div>
    </div>
    <div class="project_description">
        <a href="/projects/{{ i.slug }}/"><p class="projects_title">{{ i.title }}</p></a>
        <p class="projects_description">{{ i.description|safe|removetags:"p br div"|truncatewords:9 }} <a href="/projects/{{ i.slug }}/"><span>see more »</span></a></p>
    </div>
</div>

我检查了其他类似的主题,不知道我在这里缺少什么:(

1 个答案:

答案 0 :(得分:4)

如果i是持有个人project的变量(根据HTML中的上下文判断),则需要:

{% for client in i.client.all %}
    {{ client }}
{% endfor %}