def legislators(request, abbr):
    '''
    Context:
        - metadata
        - chamber
        - chamber_title
        - chamber_select_template
        - chamber_select_collection
        - chamber_select_chambers
        - show_chamber_column
        - abbr
        - legislators
        - sort_order
        - sort_key
        - legislator_table
        - nav_active

    Templates:
        - billy/web/public/legislators.html
        - billy/web/public/chamber_select_form.html
        - billy/web/public/legislator_table.html
    '''
    try:
        meta = Metadata.get_object(abbr)
    except DoesNotExist:
        raise Http404

    spec = {'active': True, 'district': {'$exists': True}}

    chambers = dict((k, v['name']) for k, v in meta['chambers'].items())

    chamber = request.GET.get('chamber', 'both')
    if chamber in chambers:
        spec['chamber'] = chamber
        chamber_title = meta['chambers'][chamber]['title'] + 's'
    else:
        chamber = 'both'
        chamber_title = 'Legislators'

    fields = mongo_fields('leg_id', 'full_name', 'photo_url', 'district',
                          'party', 'first_name', 'last_name', 'chamber',
                          billy_settings.LEVEL_FIELD, 'last_name')

    sort_key = 'district'
    sort_order = 1

    if request.GET:
        sort_key = request.GET.get('key', sort_key)
        sort_order = int(request.GET.get('order', sort_order))

    legislators = meta.legislators(extra_spec=spec, fields=fields)

    def sort_by_district(obj):
        matchobj = re.search(r'\d+', obj.get('district', '') or '')
        if matchobj:
            return int(matchobj.group())
        else:
            return obj.get('district', '')

    legislators = sorted(legislators, key=sort_by_district)

    if sort_key != 'district':
        legislators = sorted(legislators, key=operator.itemgetter(sort_key),
                             reverse=(sort_order == -1))
    else:
        legislators = sorted(legislators, key=sort_by_district,
                             reverse=bool(0 > sort_order))

    sort_order = {1: -1, -1: 1}[sort_order]
    legislators = list(legislators)

    return TemplateResponse(
        request, templatename('legislators'),
        dict(metadata=meta, chamber=chamber,
             chamber_title=chamber_title,
             chamber_select_template=templatename('chamber_select_form'),
             chamber_select_collection='legislators',
             chamber_select_chambers=chambers, show_chamber_column=True,
             abbr=abbr, legislators=legislators, sort_order=sort_order,
             sort_key=sort_key,
             legislator_table=templatename('legislator_table'),
             nav_active='legislators'))