autocomplete.py 3.46 KB
Newer Older
Bach Dániel committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright 2014 Budapest University of Technology and Economics (BME IK)
#
# This file is part of CIRCLE Cloud.
#
# CIRCLE is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# CIRCLE is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along
# with CIRCLE.  If not, see <http://www.gnu.org/licenses/>.

18 19
import json
from dal import autocomplete
20
from django.contrib.auth.models import User
21
from django.utils.html import escape
22
from django.utils.translation import ugettext as _
23 24
from django.db.models import Q
from django.http import HttpResponse
25

26 27
from ..views import AclUpdateView
from ..models import Profile
28 29


30 31 32 33 34 35 36 37 38 39 40 41 42 43
def highlight(field, q, none_wo_match=True):
    """
    >>> highlight('<b>Akkount Krokodil', 'kro', False)
    u'&lt;b&gt;Akkount <span class="autocomplete-hl">Kro</span>kodil'
    """

    if not field:
        return None
    try:
        match = field.lower().index(q.lower())
    except ValueError:
        match = None
    if q and match is not None:
        match_end = match + len(q)
44 45 46 47
        return (escape(field[:match]) +
                '<span class="autocomplete-hl">' +
                escape(field[match:match_end]) +
                '</span>' + escape(field[match_end:]))
48 49 50 51 52 53
    elif none_wo_match:
        return None
    else:
        return escape(field)


54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
class AclUserAutocomplete(autocomplete.Select2ListView):
    search_fields = ('first_name', 'last_name', 'username',
                     'email', 'profile__org_id')

    def filter(self, qs, search_fields):
        if self.q:
            condition = Q()
            for field in search_fields:
                condition |= Q(**{field + '__icontains': unicode(self.q)})
            return list(qs.filter(condition))
        return []

    def get_list(self):
        users = AclUpdateView.get_allowed_users(self.request.user)
        return self.filter(users, self.search_fields)
69

70 71
    def choice_displayed_text(self, choice):
        q = unicode(self.request.GET.get('q', ''))
72
        name = highlight(unicode(choice), q, False)
73
        if isinstance(choice, User):
74 75
            extra_fields = [highlight(choice.get_full_name(), q, False),
                            highlight(choice.email, q)]
76
            try:
77
                extra_fields.append(highlight(choice.profile.org_id, q))
78 79 80 81 82
            except Profile.DoesNotExist:
                pass
            return '%s (%s)' % (name, ', '.join(f for f in extra_fields
                                                if f))
        else:
83
            return _('%s (group)') % name
84

85 86 87 88 89
    def get(self, *args, **kwargs):
        return HttpResponse(json.dumps({
            'results': [dict(id=unicode(r), text=self.choice_displayed_text(r))
                        for r in self.get_list()]
        }), content_type="application/json")
90 91


92 93
class AclUserGroupAutocomplete(AclUserAutocomplete):
    group_search_fields = ('name', 'groupprofile__org_id')
94

95 96 97 98
    def get_list(self):
        groups = AclUpdateView.get_allowed_groups(self.request.user)
        groups = self.filter(groups, self.group_search_fields)
        return super(AclUserGroupAutocomplete, self).get_list() + groups