0

I have a list of jobs, each being part of a group:

class Job(models.Model):
    name = models.CharField(max_length = 200)
    group = models.CharField(max_length = 200)

How can I display a SelectField, in which groups appear highlighted and corresponding jobs are listed below?

I have seen this this post which my be a first step, but I would like more details.

thanks

Community
  • 1
  • 1
Mermoz
  • 14,898
  • 17
  • 60
  • 85

2 Answers2

1

You might want to think about making group a ForeignKey to a Group model, but with the model given you could take advantage of the fact that Django forms' ChoiceFields allow you to specify groups for choices, which are rendered as <optgroup>s:

from itertools import groupby
from operator import attrgetter

from django import forms

from myapp.models import Job

def get_grouped_job_choices():
    choices = []
    for group, jobs in groupby(Job.objects.all().order_by('group', 'name'),
                               attrgetter('group')):
        choices.append((group, [(job.pk, job.name) for job in jobs]))
    return choices

class ExampleForm(forms.Form):
    job = forms.ChoiceField(choices=get_grouped_job_choices)
Jonny Buchanan
  • 61,926
  • 17
  • 143
  • 150
  • I really like the method but I have the following error: `Caught TypeError while rendering: 'function' object is not iterable` and i don't see where it comes from. – Mermoz Dec 07 '10 at 19:23
  • ok, this comes from the fact that you forgot the brackets in `job = forms.ChoiceField(choices=get_grouped_job_choices())` – Mermoz Dec 07 '10 at 19:27
  • To use this in a model instead of a form you need to use an `IntegerField` and not a `CharField` (see http://osdir.com/ml/django-users/2010-05/msg00760.html) otherwise you get a "Value error" – Mermoz Dec 08 '10 at 14:05
1

insin has provided a good view way of doing it.

But, there is a builtin django template tag to do just that!

You can do it using the regroup template tag.

From the docmentation,

{% regroup job by group as group_list %}

<ul>
{% for group in gender_list %}
    <li>{{ group.grouper }}
    <ul>
        {% for item in group.list %}
        <li>{{ item }} </li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>
lprsd
  • 84,407
  • 47
  • 135
  • 168