开发者

Django: how to highlight groups in a `SelectField`?

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 app开发者_运维知识库ear 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


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)


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜