def render(self, name, value, attrs=None):
        if value is None:
            value = ""

        display = ""
        if self.url:
            url = self.url
            display = self.initial_display

        else:
            dc, dc, query = pickle.loads(_simple_autocomplete_queryset_cache[self.token])
            queryset = QuerySet(model=self.model, query=query)
            threshold = get_threshold_for_model(self.model)
            if threshold and (queryset.count() < threshold):
                # Render the normal select widget if size below threshold
                return super(AutoCompleteWidget, self).render(name, value, attrs)
            else:
                url = reverse("simple-autocomplete", args=[self.token])
                fieldname = get_search_fieldname(self.model)
                if value:
                    display = getattr(queryset.get(pk=value), fieldname)

            html = """
    <script type="text/javascript">
    $(document).ready(function(){

    $("#id_%(name)s_helper").autocomplete({
        source: function(request, response){
            $.ajax({
                url: "%(url)s",
                data: {q: request.term},
                success: function(data) {
                    if (data != 'CACHE_MISS')
                        response($.map(data, function(item) {
                            return {
                                label: item[1],
                                value: item[1],
                                real_value: item[0]
                            };
                        }));
                },
                dataType: "json"
            });
        },
        select: function(event, ui) { $('#id_%(name)s').val(ui.item.real_value); },
        minLength: 3
    });

    });
    </script>

<input id="id_%(name)s_helper" type="text" value="%(display)s" />
<a href="#" title="Clear" onclick="$('#id_%(name)s_helper').val(''); $('#id_%(name)s').val(''); return false;">x<small></small></a>
<input name="%(name)s" id="id_%(name)s" type="hidden" value="%(value)s" />""" % dict(
                name=name, url=url, display=display, value=value
            )
            return mark_safe(html)
def get_json(request, token):
    """Return matching results as JSON"""
    result = []
    searchtext = request.GET['q']
    if len(searchtext) >= 1:
        pickled = _simple_autocomplete_queryset_cache.get(token, None)
        if pickled is not None:
            app_label, model_name, query = pickle.loads(pickled)
            model = get_model(app_label, model_name)
            queryset = QuerySet(model=model, query=query)
            fieldname = get_search_fieldname(model)
            di = {'%s__istartswith' % fieldname: searchtext}
            items = queryset.filter(**di).order_by(fieldname)[:10]
            for item in items:
                result.append((item.id, getattr(item, fieldname)))
        else:
            result = 'CACHE_MISS'
    return HttpResponse(simplejson.dumps(result))
Ejemplo n.º 3
0
def get_json(request, token):
    """Return matching results as JSON"""
    result = []
    searchtext = request.GET['q']
    if len(searchtext) >= 3:
        pickled = _simple_autocomplete_queryset_cache.get(token, None)
        if pickled is not None:
            app_label, model_name, query = pickle.loads(pickled)
            model = apps.get_model(app_label, model_name)
            queryset = QuerySet(model=model, query=query)
            fieldname = get_search_fieldname(model)
            di = {'%s__istartswith' % fieldname: searchtext}
            app_label_model = '%s.%s' % (app_label, model_name)
            max_items = get_setting(app_label_model, 'max_items', 10)
            items = queryset.filter(**di).order_by(fieldname)[:max_items]

            # Check for duplicate strings
            counts = {}
            for item in items:
                key = unicode(item)
                counts.setdefault(key, 0)
                counts[key] += 1

            # Assemble result set
            for item in items:
                key = value = unicode(item)
                value = getattr(item, fieldname)
                if counts[key] > 1:
                    func = get_setting(
                        app_label_model,
                        'duplicate_format_function',
                        lambda obj, model, content_type: content_type.name
                    )
                    content_type = ContentType.objects.get_for_model(model)
                    value = '%s (%s)' % (value, func(item, model, content_type))
                result.append((item.id, value))

        else:
            result = 'CACHE_MISS'

    return HttpResponse(json.dumps(result))
def get_json(request, token):
    """Return matching results as JSON"""
    result = []
    searchtext = request.GET['q']
    if len(searchtext) >= 3:
        pickled = _simple_autocomplete_queryset_cache.get(token, None)
        if pickled is not None:
            app_label, model_name, query = pickle.loads(pickled)
            model = apps.get_model(app_label, model_name)
            queryset = QuerySet(model=model, query=query)
            fieldname = get_search_fieldname(model)
            di = {'%s__istartswith' % fieldname: searchtext}
            app_label_model = '%s.%s' % (app_label, model_name)
            max_items = get_setting(app_label_model, 'max_items', 10)
            items = queryset.filter(**di).order_by(fieldname)[:max_items]

            # Check for duplicate strings
            counts = {}
            for item in items:
                key = unicode(item)
                counts.setdefault(key, 0)
                counts[key] += 1

            # Assemble result set
            for item in items:
                key = value = unicode(item)
                value = getattr(item, fieldname)
                if counts[key] > 1:
                    func = get_setting(
                        app_label_model, 'duplicate_format_function',
                        lambda obj, model, content_type: content_type.name)
                    content_type = ContentType.objects.get_for_model(model)
                    value = '%s (%s)' % (value, func(item, model,
                                                     content_type))
                result.append((item.id, value))

        else:
            result = 'CACHE_MISS'

    return HttpResponse(json.dumps(result))
Ejemplo n.º 5
0
    def render(self, name, value, attrs=None):
        if value is None:
            value = []

        display = ''
        if self.url:
            url = self.url
            # todo: Display is not so simple in this case. Needs a lot of work.
            # Will probably have to be a dictionary.
            display = self.initial_display
        else:
            dc, dc, query = pickle.loads(
                _simple_autocomplete_queryset_cache[self.token]
            )
            queryset = QuerySet(model=self.model, query=query)
            threshold = get_threshold_for_model(self.model)
            if threshold and (queryset.count() < threshold):
                # Render the normal select widget if size below threshold
                return super(AutoCompleteMultipleWidget, self).render(
                    name, value, attrs
                )
            else:
                url = reverse('simple-autocomplete', args=[self.token])
                fieldname = get_search_fieldname(self.model)

            html = u"""
    <script type="text/javascript">
    $(document).ready(function(){

    $("#id_%s_helper").autocomplete({
        source: function(request, response){
            $.ajax({
                url: "%s",
                data: {q: request.term},
                success: function(data) {
                    if (data != 'CACHE_MISS')
                    {
                        response($.map(data, function(item) {
                            return {
                                label: item[1],
                                value: item[1],
                                real_value: item[0]
                            };
                        }));
                    }
                },
                dataType: "json"
            });
        },
        select: function(event, ui) {
            var name = '%s';
            var parent = $('#id_' + name).parent();
            var target = $('div.autocomplete-placeholder', parent);
            target.append('<p><input name="' + name + '" value="' + ui.item.real_value + '" ' 
                + 'type="hidden" />' + ui.item.value 
                + ' <a href="#" title="Remove" onclick="$(this).parent().remove(); $('+"'"+'#id_%s_helper'+"'"+').val(' + "''" + '); $('+"'"+'#id_%s_helper'+"'"+').focus(); return false;">x<small></small></a></p>');
        },
        close: function(event, ui) {
            $('#id_%s_helper').val('');
        },
        minLength: 3
    });

    });
    </script>

<input id="id_%s_helper" type="text" value="" />
<input id="id_%s" type="hidden" value="" />
<div class="autocomplete-placeholder">""" % (name, url, name, name, name, name, name, name)

            # Create html for existing values
            for v in value:
                display = unicode(queryset.get(pk=v))
                html += """<p><input name="%s" type="hidden" value="%s" />
%s <a href="#" title="Remove" onclick="$(this).parent().remove(); $('#id_%s_helper').val(''); $('#id_%s_helper').focus(); return false;">x<small></small></a></p>""" % (name, v, display, name, name)

            html += "</div>"

            # Help with green plus icon alignment
            # todo: use css class
            html += """<div style="display: inline-block; width: 104px;">&nbsp;</div>"""

            return mark_safe(html)
Ejemplo n.º 6
0
    def render(self, name, value, attrs=None):
        if value is None:
            value = ''

        display = ''
        if self.url:
            url = self.url
            display = self.initial_display

        else:
            dc, dc, query = pickle.loads(
                _simple_autocomplete_queryset_cache[self.token]
            )
            queryset = QuerySet(model=self.model, query=query)
            threshold = get_threshold_for_model(self.model)
            if threshold and (queryset.count() < threshold):
                # Render the normal select widget if size below threshold
                return super(AutoCompleteWidget, self).render(
                    name, value, attrs
                )
            else:
                url = reverse('simple-autocomplete', args=[self.token])
                fieldname = get_search_fieldname(self.model)
                if value:
                    display = getattr(queryset.get(pk=value), fieldname)

        html = u"""
    <script type="text/javascript">
    $(document).ready(function(){

    $("#id_%(name)s_helper").autocomplete({
        source: function(request, response){
            $.ajax({
                url: "%(url)s",
                data: {q: request.term},
                success: function(data) {
                    if (data != 'CACHE_MISS')
                    {
                        response($.map(data, function(item) {
                            return {
                                label: item[1],
                                value: item[1],
                                real_value: item[0]
                            };
                        }));
                    }
                },
                dataType: "json"
            });
        },
        select: function(event, ui) { $('#id_%(name)s').val(ui.item.real_value); },
        minLength: 1
    });

    });
    </script>

<input id="id_%(name)s_helper" type="text" value="%(display)s" />
<a href="#" title="Clear" onclick="$('#id_%(name)s_helper').val(''); $('#id_%(name)s_helper').focus(); $('#id_%(name)s').val(''); return false;">x<small></small></a>
<input name="%(name)s" id="id_%(name)s" type="hidden" value="%(value)s" />""" % dict(name=name, url=url, display=display, value=value)
        return mark_safe(html)
Ejemplo n.º 7
0
    def render(self, name, value, attrs=None):
        if value is None:
            value = []

        display = ''
        if self.url:
            url = self.url
            # todo: Display is not so simple in this case. Needs a lot of work.
            # Will probably have to be a dictionary.
            display = self.initial_display
        else:
            dc, dc, query = pickle.loads(
                _simple_autocomplete_queryset_cache[self.token]
            )
            queryset = QuerySet(model=self.model, query=query)
            threshold = get_threshold_for_model(self.model)
            if threshold and (queryset.count() < threshold):
                # Render the normal select widget if size below threshold
                return super(AutoCompleteMultipleWidget, self).render(
                    name, value, attrs
                )
            else:
                url = reverse('simple-autocomplete', args=[self.token])
                fieldname = get_search_fieldname(self.model)

            html = u"""
    <script type="text/javascript">
    $(document).ready(function(){

    $("#id_%s_helper").autocomplete({
        source: function(request, response){
            $.ajax({
                url: "%s",
                data: {q: request.term},
                success: function(data) {
                    if (data != 'CACHE_MISS')
                        response($.map(data, function(item) {
                            return {
                                label: item[1],
                                value: item[1],
                                real_value: item[0]
                            };
                        }));
                },
                dataType: "json"
            });
        },
        select: function(event, ui) {
            var name = '%s';
            var parent = $('#id_' + name).parent();
            var target = $('div.autocomplete-placeholder', parent);
            target.append('<p><input name="' + name + '" value="' + ui.item.real_value + '" ' 
                + 'type="hidden" />' + ui.item.value 
                + ' <a href="#" title="Remove" onclick="$(this).parent().remove(); $('+"'"+'#id_%s_helper'+"'"+').val(' + "''" + '); $('+"'"+'#id_%s_helper'+"'"+').focus(); return false;">x<small></small></a></p>');
        },
        close: function(event, ui) {
            $('#id_%s_helper').val('');
        },
        minLength: 3
    });

    });
    </script>

<input id="id_%s_helper" type="text" value="" />
<input id="id_%s" type="hidden" value="" />
<div class="autocomplete-placeholder">""" % (name, url, name, name, name, name, name, name)

            # Create html for existing values
            for v in value:
                display = getattr(queryset.get(pk=v), fieldname)
                html += """<p><input name="%s" type="hidden" value="%s" />
%s <a href="#" title="Remove" onclick="$(this).parent().remove(); $('#id_%s_helper').val(''); $('#id_%s_helper').focus(); return false;">x<small></small></a></p>""" % (name, v, display, name, name)

            html += "</div>"

            # Help with green plus icon alignment
            # todo: use css class
            html += """<div style="display: inline-block; width: 104px;">&nbsp;</div>"""

            return mark_safe(html)