• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python utils.unicode_sorter函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中smart_selects.utils.unicode_sorter函数的典型用法代码示例。如果您正苦于以下问题:Python unicode_sorter函数的具体用法?Python unicode_sorter怎么用?Python unicode_sorter使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了unicode_sorter函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: filterchain_all

def filterchain_all(request, app, model):
    model_class = get_model(app, model)
    keywords = {}
    for field, value in request.GET.items():
        if value == '0':
            keywords[str("%s__isnull" % field)] = True
        elif value:
            keywords[str(field)] = str(value) or None

    queryset = model_class._default_manager.filter(**keywords)
    if not len(keywords):
        queryset = queryset.none()

    results = list(queryset)
    results.sort(cmp=locale.strcoll, key=lambda x: unicode_sorter(unicode(x)))
    final = []
    for item in results:
        final.append({'value': item.pk, 'display': unicode(item)})
    results = list(model_class._default_manager.exclude(**keywords))
    results.sort(cmp=locale.strcoll, key=lambda x: unicode_sorter(unicode(x)))
    final.append({'value': "", 'display': "---------"})

    for item in results:
        final.append({'value': item.pk, 'display': unicode(item)})
    json = simplejson.dumps(final)
    return HttpResponse(json, content_type='application/json')
开发者ID:AndreLobato,项目名称:raizcidadanista,代码行数:26,代码来源:views.py


示例2: filterchain

def filterchain(request, app, model, manager=None):
    model_class = get_model(app, model)
    keywords = {}
    for field, value in request.GET.items():
        if value == '0':
            keywords[str("%s__isnull" % field)] = True
        elif value:
            keywords[str(field)] = str(value) or None

    if manager is not None and hasattr(model_class, manager):
        queryset = getattr(model_class, manager)
    else:
        queryset = model_class._default_manager

    results = queryset.filter(**keywords)
    if not len(keywords):
        results = results.none()

    if not getattr(model_class._meta, 'ordering', False):
        results = list(results)
        results.sort(cmp=locale.strcoll, key=lambda x: unicode_sorter(unicode(x)))

    result = []
    for item in results:
        result.append({'value': item.pk, 'display': unicode(item)})
    json = simplejson.dumps(result)
    return HttpResponse(json, content_type='application/json')
开发者ID:AndreLobato,项目名称:raizcidadanista,代码行数:27,代码来源:views.py


示例3: filterchain_all

def filterchain_all(request, app, model, field, value):
    Model = get_model(app, model)
    keywords = {str(field): str(value)}
    results = list(Model.objects.filter(**keywords))
    results.sort(cmp=locale.strcoll, key=lambda x:unicode_sorter(unicode(x)))
    final = []
    for item in results:
        final.append({'value':item.pk, 'display':unicode(item)})
    results = list(Model.objects.exclude(**keywords))
    results.sort(cmp=locale.strcoll, key=lambda x:unicode_sorter(unicode(x)))
    final.append({'value':"", 'display':"---------"})
    
    for item in results:
        final.append({'value':item.pk, 'display':unicode(item)})
    json = simplejson.dumps(final)
    return HttpResponse(json, mimetype='application/json')
开发者ID:Anber,项目名称:django-smart-selects,代码行数:16,代码来源:views.py


示例4: filterchain

def filterchain(request, app, model, field, manager=None):
    model_class = get_model(app, model)
    queryset = model_class._default_manager
    results = list(queryset.all().values_list('option_name'))
    results.sort(cmp=locale.strcoll, key=lambda x: unicode_sorter(unicode(x)))
    json = simplejson.dumps(results)
    return HttpResponse(json, mimetype='application/json')
开发者ID:pygaur,项目名称:taxiforpool,代码行数:7,代码来源:views.py


示例5: filterchain_all

def filterchain_all(request, app, model, field, value):
    model_class = get_model(app, model)
    if value == "0":
        keywords = {str("%s__isnull" % field): True}
    else:
        keywords = {str(field): str(value)}
    results = list(model_class._default_manager.filter(**keywords))
    results.sort(cmp=strcoll, key=lambda x: unicode_sorter(unicode(x)))
    final = []
    for item in results:
        final.append({"value": item.pk, "display": unicode(item)})
    results = list(model_class._default_manager.exclude(**keywords))
    results.sort(cmp=strcoll, key=lambda x: unicode_sorter(unicode(x)))
    final.append({"value": "", "display": "---------"})
    for item in results:
        final.append({"value": item.pk, "display": unicode(item)})
    return HttpResponse(dumps(final), mimetype="application/json")
开发者ID:emergence,项目名称:django-smart-selects,代码行数:17,代码来源:views.py


示例6: filterchain_all

def filterchain_all(request, app, model, field, value):
    model_class = get_model(app, model)
    if value == '0':
        keywords = {str("%s__isnull" % field): True}
    else:
        keywords = {str(field): str(value)}
    results = list(model_class._default_manager.filter(**keywords))
    results.sort(cmp=locale.strcoll, key=lambda x: unicode_sorter(unicode(x)))
    final = []
    for item in results:
        final.append({'value': item.pk, 'display': unicode(item)})
    results = list(model_class._default_manager.exclude(**keywords))
    results.sort(cmp=locale.strcoll, key=lambda x: unicode_sorter(unicode(x)))
    final.append({'value': "", 'display': "---------"})

    for item in results:
        final.append({'value': item.pk, 'display': unicode(item)})
    json = simplejson.dumps(final)
    return HttpResponse(json, mimetype='application/json')
开发者ID:Japje,项目名称:django-smart-selects,代码行数:19,代码来源:views.py


示例7: filterchain

def filterchain(request, app, model, field, value):
    Model = get_model(app, model)
    if value == '0':
        keywords = {str("%s__isnull" % field):True}
    else:
        keywords = {str(field): str(value)}
    results = list(Model.objects.filter(**keywords))
    results.sort(cmp=locale.strcoll, key=lambda x:unicode_sorter(unicode(x)))
    result = []
    for item in results:
        result.append({'value':item.pk, 'display':unicode(item)})
    json = simplejson.dumps(result)
    return HttpResponse(json, mimetype='application/json')
开发者ID:AndresDileva,项目名称:ProyectoFinal,代码行数:13,代码来源:views.py


示例8: filterchain

def filterchain(request, app, model, field, value, manager=None):
    Model = get_model(app, model)
    keywords = {str(field): str(value)}
    if manager is not None and hasattr(Model, manager):
        queryset = getattr(Model, manager).all()
    else:
        queryset = Model.objects
    results = list(queryset.filter(**keywords))
    results.sort(cmp=locale.strcoll, key=lambda x:unicode_sorter(unicode(x)))
    result = []
    for item in results:
        result.append({'value':item.pk, 'display':unicode(item)})
    json = simplejson.dumps(result)
    return HttpResponse(json, mimetype='application/json')
开发者ID:bitzeppelin,项目名称:django-smart-selects,代码行数:14,代码来源:views.py


示例9: filterchain

def filterchain(request, app, model, field, value, manager=None):
    model_class = get_model(app, model)
    if value == "0":
        keywords = {str("%s__isnull" % field): True}
    else:
        keywords = {str(field): str(value)}
    if manager is not None and hasattr(model_class, manager):
        queryset = getattr(model_class, manager)
    else:
        queryset = model_class._default_manager
    results = list(queryset.filter(**keywords))
    results.sort(cmp=strcoll, key=lambda x: unicode_sorter(unicode(x)))
    result = []
    for item in results:
        result.append({"value": item.pk, "display": unicode(item)})
    return HttpResponse(dumps(result), mimetype="application/json")
开发者ID:emergence,项目名称:django-smart-selects,代码行数:16,代码来源:views.py


示例10: filterchain

def filterchain(request, app, model, field, value, manager=None):
    model_class = get_model(app, model)
    if value == '0':
        keywords = {str("%s__isnull" % field): True}
    else:
        keywords = {str(field): str(value)}
    if manager is not None and hasattr(model_class, manager):
        queryset = getattr(model_class, manager)
    else:
        queryset = model_class._default_manager
    results = list(queryset.filter(**keywords))
    results.sort(cmp=locale.strcoll, key=lambda x: unicode_sorter(unicode(x)))
    result = []
    for item in results:
        result.append({'value': item.pk, 'display': unicode(item)})
    json_response = json.dumps(result)
    return HttpResponse(json_response, content_type='application/json')
开发者ID:kabucey,项目名称:django-smart-selects,代码行数:17,代码来源:views.py


示例11: filterchain

def filterchain(request, app, model, field, value, manager=None):
    model_class = get_model(app, model)
    try:
        political_divisions = model_class.country.field.related.parent_model.objects.get(id=value).political_divisions
    except:
        political_divisions = "State"
    if value == '0':
        keywords = {str("%s__isnull" % field): True}
    else:
        keywords = {str(field): str(value)}
    if manager is not None and hasattr(model_class, manager):
        queryset = getattr(model_class, manager)
    else:
        queryset = model_class._default_manager
    results = list(queryset.filter(**keywords))
    results.sort(cmp=locale.strcoll, key=lambda x: unicode_sorter(unicode(x)))
    result = {'out': [],}    
    for item in results:
        result['out'].append({'value': item.pk, 'display': unicode(item)})
    result['political_divisions'] = political_divisions 
    json = simplejson.dumps(result)
    return HttpResponse(json, mimetype='application/json')
开发者ID:drawingboardmedia,项目名称:django-smart-selects,代码行数:22,代码来源:views.py


示例12: filterchain_m2m

def filterchain_m2m(request, app, model, mapp, middle, field, value, manager=None):
    #middle = 'Standings'
    Model = get_model(app, model)
    Middle = get_model(mapp, middle)
    if manager is not None:
        raise HttpResponseServerError
    if value == '0':
        keywords = {str("%s__isnull" % field): True}
    else:
        keywords = {str(field): str(value)}
    if manager is not None and hasattr(Model, manager):
        queryset = getattr(Model, manager).all()
    else:
        queryset = Middle.objects
    results = list(queryset.filter(**keywords))
    results.sort(cmp=locale.strcoll, key=lambda x: unicode_sorter(unicode(x)))
    result = []
    for item in results:
        itemid = item.__dict__[model.lower() + '_id']
        result.append({'value': itemid, 'display': unicode(Model.objects.get(pk=itemid))})
    json = simplejson.dumps(result)
    return HttpResponse(json, mimetype='application/json')
开发者ID:skotsjedal,项目名称:caglol,代码行数:22,代码来源:views.py


示例13: render

    def render(self, name, value, attrs=None, choices=()):
        if len(name.split('-')) > 1:  # formset
            chained_field = '-'.join(name.split('-')[:-1] + [self.chained_field])
        else:
            chained_field = self.chained_field

        if not self.view_name:
            if self.show_all:
                view_name = "chained_filter_all"
            else:
                view_name = "chained_filter"
        else:
            view_name = self.view_name
        kwargs = {
            'app': self.to_app_name,
            'model': self.to_model_name,
            'field': self.chained_model_field,
            'foreign_key_app_name': self.foreign_key_app_name,
            'foreign_key_model_name': self.foreign_key_model_name,
            'foreign_key_field_name': self.foreign_key_field_name,
            'value': '1'
            }
        if self.manager is not None:
            kwargs.update({'manager': self.manager})
        url = URL_PREFIX + ("/".join(reverse(view_name, kwargs=kwargs).split("/")[:-2]))
        if self.auto_choose:
            auto_choose = 'true'
        else:
            auto_choose = 'false'
        iterator = iter(self.choices)
        if hasattr(iterator, '__next__'):
            empty_label = iterator.__next__()[1]
        else:
            # Hacky way to getting the correct empty_label from the field instead of a hardcoded '--------'
            empty_label = iterator.next()[1]

        js = """
        <script type="text/javascript">
        (function($) {
            var chainfield = "#id_%(chainfield)s";
            var url = "%(url)s";
            var id = "#%(id)s";
            var value = %(value)s;
            var auto_choose = %(auto_choose)s;
            var empty_label = "%(empty_label)s";

            $(document).ready(function() {
                chainedfk.init(chainfield, url, id, value, empty_label, auto_choose);
            });
        })(jQuery || django.jQuery);
        </script>

        """
        js = js % {"chainfield": chained_field,
                   "url": url,
                   "id": attrs['id'],
                   'value': 'undefined' if value is None or value == '' else value,
                   'auto_choose': auto_choose,
                   'empty_label': escape(empty_label)}
        final_choices = []
        if value:
            available_choices = self._get_available_choices(self.queryset, value)
            for choice in available_choices:
                final_choices.append((choice.pk, force_text(choice)))
        if len(final_choices) > 1:
            final_choices = [("", (empty_label))] + final_choices
        if self.show_all:
            final_choices.append(("", (empty_label)))
            self.choices = list(self.choices)
            self.choices.sort(key=lambda x: unicode_sorter(x[1]))
            for ch in self.choices:
                if ch not in final_choices:
                    final_choices.append(ch)
        self.choices = ()
        final_attrs = self.build_attrs(attrs, name=name)
        if 'class' in final_attrs:
            final_attrs['class'] += ' chained'
        else:
            final_attrs['class'] = 'chained'

        output = super(ChainedSelect, self).render(name, value, final_attrs, choices=final_choices)
        output += js
        return mark_safe(output)
开发者ID:anlaplante,项目名称:mahana,代码行数:83,代码来源:widgets.py


示例14: render


#.........这里部分代码省略.........
                    if (init_value == "None") init_value = undefined;
                    var url = "%(url)s/";
                    if (!val && pk)
                        url += "0/pk/"+pk;
                    else
                        url += val;
                    $.getJSON(url+"/", function(j){
                        var options = '<option value="">%(empty_label)s<'+'/option>';
                        var prev_value = el.children("option[selected='selected']").val();
                        for (var i = 0; i < j.length; i++) {
                            options += '<option value="' + j[i].value + '">' + j[i].display + '<'+'/option>';
                        }
                        var width = el.outerWidth();
                        el.html(options);
                        if (navigator.appVersion.indexOf("MSIE") != -1)
                            el.width(width + 'px');
                        $('#%(id)s option:first').attr('selected', 'selected');
                        var auto_choose = %(auto_choose)s;
                        if(init_value){
                            $('#%(id)s option[value="'+ init_value +'"]').attr('selected', 'selected');
                        }
                        if(auto_choose && j.length == 1){
                            $('#%(id)s option[value="'+ j[0].value +'"]').attr('selected', 'selected');
                        }
                        if (init_value != prev_value)
                            el.trigger('change');
                    })
                }

                var chainfield = $("#id_%(chainfield)s");

                if(!chainfield.hasClass("chained") || !el.children().length){
                    var pk;
                    var val = chainfield.val();
                    if (!chainfield.length) {
                        var a;
                        a = el.parents("tr").first().children("td.action-checkbox").children("input.action-select");
                        if (a.length)
                            pk = a.val();
                        else {
                            a = el.parents("div.inline-group");
                            if (a.length)
                                val = document.location.pathname.match(/\d+[/]?$/)[0].replace("/","");
                        }
                    }
                    fill_field(val, "%(value)s", pk);
                }

                chainfield.change(function(){
                    var start_value = el.val();
                    var val = $(this).val();
                    fill_field(val, start_value);
                })
            })
            if (typeof(dismissAddAnotherPopup) !== 'undefined') {
                var oldDismissAddAnotherPopup = dismissAddAnotherPopup;
                dismissAddAnotherPopup = function(win, newId, newRepr) {
                    oldDismissAddAnotherPopup(win, newId, newRepr);
                    if (windowname_to_id(win.name) == "id_%(chainfield)s") {
                        $("#id_%(chainfield)s").change();
                    }
                }
            }
        })(jQuery || django.jQuery);
        //]]>
        </script>

        """
        js = js % {
            "chainfield": chain_field.split("__")[0],
            "url": url,
            "id": attrs["id"],
            "value": value,
            "auto_choose": auto_choose,
            "empty_label": empty_label,
        }
        final_choices = []
        if value:
            available_choices = self._get_available_choices(self.queryset, value)
            for choice in available_choices:
                final_choices.append((choice.pk, force_text(choice)))
        if len(final_choices) > 1:
            final_choices = [("", (empty_label))] + final_choices
        if self.show_all:
            final_choices.append(("", (empty_label)))
            self.choices = list(self.choices)
            self.choices.sort(key=lambda x: unicode_sorter(x[1]))
            for ch in self.choices:
                if not ch in final_choices:
                    final_choices.append(ch)
        self.choices = ()
        final_attrs = self.build_attrs(attrs, name=name)
        if "class" in final_attrs:
            final_attrs["class"] += " chained"
        else:
            final_attrs["class"] = "chained"

        output = super(ChainedSelect, self).render(name, value, final_attrs, choices=final_choices)
        output += js
        return mark_safe(output)
开发者ID:mkaluza,项目名称:django-smart-selects,代码行数:101,代码来源:widgets.py


示例15: render

 def render(self, name, value, attrs=None, choices=()):
     if len(name.split('-')) > 1: # formset
         chain_field = '-'.join(name.split('-')[:-1] + [self.chain_field])
     else:
         chain_field = self.chain_field 
     
     if self.show_all:
         url = "/".join(reverse("chained_filter_all", kwargs={'app':self.app_name,'model':self.model_name,'field':self.model_field,'value':"1"}).split("/")[:-2])
     else:
         url = "/".join(reverse("chained_filter", kwargs={'app':self.app_name,'model':self.model_name,'field':self.model_field,'value':"1"}).split("/")[:-2])
     if self.auto_choose:
         auto_choose = 'true'
     else:
         auto_choose = 'false'
     empty_label = iter(self.choices).next()[1] # Hacky way to getting the correct empty_label from the field instead of a hardcoded '--------'
     js = """
     <script type="text/javascript">
     //<![CDATA[
     $(document).ready(function(){
         function fill_field(val, init_value){
             if (!val || val==''){
                 options = '<option value="">%(empty_label)s<'+'/option>';
                 $("#%(id)s").html(options);
                 $('#%(id)s option:first').attr('selected', 'selected');
                 $("#%(id)s").trigger('change');
                 return;
             }
             $.getJSON("%(url)s/"+val+"/", function(j){
                 var options = '<option value="">%(empty_label)s<'+'/option>';
                 for (var i = 0; i < j.length; i++) {
                     options += '<option value="' + j[i].value + '">' + j[i].display + '<'+'/option>';
                 }
                 $("#%(id)s").html(options);
                 $('#%(id)s option:first').attr('selected', 'selected');
                 var auto_choose = %(auto_choose)s;
                 if(init_value){
                     $('#%(id)s option[value="'+ init_value +'"]').attr('selected', 'selected');
                 }
                 if(auto_choose && j.length == 1){
                     $('#%(id)s option[value="'+ j[0].value +'"]').attr('selected', 'selected');
                 }
                 $("#%(id)s").trigger('change');
             })
         }
         
         if(!$("select#id_%(chainfield)s").hasClass("chained")){
             var val = $("select#id_%(chainfield)s").val();
             fill_field(val, "%(value)s");
         }
         
         $("select#id_%(chainfield)s").change(function(){
             var start_value = $("select#%(id)s").val();
             var val = $(this).val();
             fill_field(val, start_value);
             
         })
     })
     //]]>
     </script>
     
     """ % {"chainfield":chain_field, "url":url, "id":attrs['id'], 'value':value, 'auto_choose':auto_choose, 'empty_label': empty_label}
     final_choices=[]
     
     if value:
         item = self.queryset.filter(pk=value)[0]
         try:
             pk = getattr(item, self.model_field+"_id")
             filter={self.model_field:pk}
         except AttributeError:
             try: # maybe m2m?
                 pks = getattr(item, self.model_field).all().values_list('pk', flat=True)
                 filter={self.model_field+"__in":pks}
             except AttributeError:
                 try: # maybe a set?
                     pks = getattr(item, self.model_field+"_set").all().values_list('pk', flat=True)
                     filter={self.model_field+"__in":pks}
                 except: # give up
                     filter = {}
         filtered = list(get_model( self.app_name, self.model_name).objects.filter(**filter).distinct())
         filtered.sort(cmp=locale.strcoll, key=lambda x:unicode_sorter(unicode(x)))
         for choice in filtered:
             final_choices.append((choice.pk, unicode(choice)))
     if len(final_choices)>1:
         final_choices = [("", (empty_label))] + final_choices
     if self.show_all:
         final_choices.append(("", (empty_label)))
         self.choices = list(self.choices)
         self.choices.sort(cmp=locale.strcoll, key=lambda x:unicode_sorter(x[1]))
         for ch in self.choices:
             if not ch in final_choices:
                 final_choices.append(ch)
     self.choices = ()
     final_attrs = self.build_attrs(attrs, name=name)
     if 'class' in final_attrs:
         final_attrs['class'] += ' chained'
     else:
         final_attrs['class'] = 'chained'
     output = super(ChainedSelect, self).render(name, value, final_attrs, choices=final_choices)
     output += js
     return mark_safe(output)
开发者ID:dmoisset,项目名称:django-smart-selects,代码行数:100,代码来源:widgets.py


示例16: render

    def render(self, name, value, attrs=None, choices=()):
        if len(name.split('-')) > 1: # formset
            chain_field = '-'.join(name.split('-')[:-1] + [self.chain_field])
        else:
            chain_field = self.chain_field

        if self.show_all:
            url = "/".join(reverse("chained_filter_all", kwargs={'app':self.app_name,'model':self.model_name,'field':self.model_field,'value':"1"}).split("/")[:-2])
        else:
            url = "/".join(reverse("chained_filter", kwargs={'app':self.app_name,'model':self.model_name,'field':self.model_field,'value':"1"}).split("/")[:-2])
        if self.auto_choose:
            auto_choose = 'true'
        else:
            auto_choose = 'false'
        empty_label = iter(self.choices).next()[1] # Hacky way to getting the correct empty_label from the field instead of a hardcoded '--------'
        js = """
        <script type="text/javascript">
        //<![CDATA[
        (function($) {
            $(document).ready(function(){
                var $chainfield = $("#id_%(chainfield)s"),
                    $select = $("#%(id)s"),
                    auto_choose = %(auto_choose)s;

                $chainfield.change(function() {
                    var chain_val = $chainfield.val(),
                        original_value = $select.val();

                    $select.empty()
                        .append($('<option value="" selected>').text('%(empty_label)s'))
                        .change();

                    if (!chain_val) {
                        $select.trigger("chain-complete");
                        return;
                    }

                    $.getJSON("%(url)s/" + chain_val + "/", function(data) {
                        for (var i = 0; i < data.length; i++) {
                            $('<option>')
                                .attr("value", data[i].value)
                                .text(data[i].display)
                                .appendTo($select);
                        }

                        $select.find("option").first().attr("selected", "selected");

                        if (original_value) {
                            // We can't simply use .val() here because it will
                            // break certain browsers if original_value is no
                            // longer present
                            $select.find('option[value="' + original_value + '"]')
                                .attr("selected", "selected");
                        }

                        if (auto_choose && data.length == 1) {
                            $select.val(data[0].value);
                        }

                        $select.change();
                        $select.trigger("chain-complete");
                    });
                });
            })
        })(django.jQuery || jQuery);
        //]]>
        </script>

        """ % {"chainfield":chain_field, "url":url, "id":attrs['id'], 'value':value, 'auto_choose':auto_choose, 'empty_label': empty_label}
        final_choices=[]

        if value:
            item = self.queryset.filter(pk=value)[0]
            try:
                pk = getattr(item, self.model_field+"_id")
                filter={self.model_field:pk}
            except AttributeError:
                try: # maybe m2m?
                    pks = getattr(item, self.model_field).all().values_list('pk', flat=True)
                    filter={self.model_field+"__in":pks}
                except AttributeError:
                    try: # maybe a set?
                        pks = getattr(item, self.model_field+"_set").all().values_list('pk', flat=True)
                        filter={self.model_field+"__in":pks}
                    except: # give up
                        filter = {}
            filtered = list(get_model( self.app_name, self.model_name).objects.filter(**filter).distinct())
            filtered.sort(cmp=locale.strcoll, key=lambda x:unicode_sorter(unicode(x)))
            for choice in filtered:
                final_choices.append((choice.pk, unicode(choice)))
        if len(final_choices)>1:
            final_choices = [("", (empty_label))] + final_choices
        if self.show_all:
            final_choices.append(("", (empty_label)))
            self.choices = list(self.choices)
            self.choices.sort(cmp=locale.strcoll, key=lambda x:unicode_sorter(x[1]))
            for ch in self.choices:
                if not ch in final_choices:
                    final_choices.append(ch)
        self.choices = ()
#.........这里部分代码省略.........
开发者ID:acdha,项目名称:django-smart-selects,代码行数:101,代码来源:widgets.py


示例17: render


#.........这里部分代码省略.........
                    else {
                        var select_state = document.createElement("select");
                        select_state = $(select_state).attr('id', '%(id)s');
                        select_state = $(select_state).attr('name', '%(name)s');
                        $('input#%(id)s').replaceWith(select_state);
                        $('#%(id)s').empty();
                        $('label[for="%(id)s"]').html(j.political_divisions);
                        var options = '<option value="">%(empty_label)s<'+'/option>';
                        for (var i = 0; i < j.out.length; i++) {
                            options += '<option value="' + j.out[i].display + '">' + j.out[i].display + '<'+'/option>';
                            if (j.out[i] == selected_state_value) {
                                options[i].selected = true;
                            }
                        }
                        selected_state_value = '';
                        var width = $("#%(id)s").outerWidth();
                        $("#%(id)s").html(options);
                        if (navigator.appVersion.indexOf("MSIE") != -1)
                            $("#%(id)s").width(width + 'px');
                        $('#%(id)s option:first').attr('selected', 'selected');
                        var auto_choose = %(auto_choose)s;
                        if(init_value){
                            $('#%(id)s option[value="'+ init_value +'"]').attr('selected', 'selected');
                        }
                        if(auto_choose && j.out.length == 1){
                            $('#%(id)s option[value="'+ j.out[0].value +'"]').attr('selected', 'selected');
                        }
                        $("#%(id)s").trigger('change');
                    }
                });
            };
            $(document).ready(function(){
                if(!$("#id_%(chainfield)s").hasClass("chained")){
                    var val = $("#id_%(chainfield)s").val();
                    fill_field(val, "%(value)s");
                }
                $("#id_%(chainfield)s").change(function(){
                    var start_value = $("#%(id)s").val();
                    var val = $(this).val();
                    fill_field(val, start_value);
                });
              
            });
            if (typeof(dismissAddAnotherPopup) !== 'undefined') {
                var oldDismissAddAnotherPopup = dismissAddAnotherPopup;
                dismissAddAnotherPopup = function(win, newId, newRepr) {
                    oldDismissAddAnotherPopup(win, newId, newRepr);
                    if (windowname_to_id(win.name) == "id_%(chainfield)s") {
                        $("#id_%(chainfield)s").change();
                    }
                }
            }
            // making function which is returning state as global so that we can call this function when we need to fill the state filled on 
            // any event in the checkout stages
            window.fill_field = fill_field
        })(jQuery || django.jQuery);
        //]]>
        </script>


        """
        js = js % {"chainfield": chain_field,
                   "url": url,
                   "id": attrs['id'],
                   "name": name	,
                   'value': value,
                   'auto_choose': auto_choose,
                   'empty_label': empty_label}
        final_choices = []
        if value:
            try:
                item = self.queryset.get(pk=value)        #  change 
                try:
                    pk = getattr(item, self.model_field + "_id")
                    filter = {self.model_field: pk}
                except AttributeError:
                    try:  # maybe m2m?
                        pks = getattr(item, self.model_field).all().values_list('pk', flat=True)
                        filter = {self.model_field + "__in": pks}
                    except AttributeError:
                        try:  # maybe a set?
                            pks = getattr(item, self.model_field + "_set").all().values_list('pk', flat=True)
                            filter = {self.model_field + "__in": pks}
                        except:  # give up
                            filter = {}
                filtered = list(get_model(self.app_name, self.model_name).objects.filter(**filter).distinct())
                filtered.sort(cmp=locale.strcoll, key=lambda x: unicode_sorter(unicode(x)))
                for choice in filtered:
                    final_choices.append((choice.pk, unicode(choice)))
            except Exception, e:
                final_choices = [(value, value)] # changes
            if len(final_choices) > 1:
                final_choices = [("", (empty_label))] + final_choices
            if self.show_all:
                final_choices.append(("", (empty_label)))
                self.choices = list(self.choices)
                self.choices.sort(cmp=locale.strcoll, key=lambda x: unicode_sorter(x[1]))
                for ch in self.choices:
                    if not ch in final_choices:
                        final_choices.append(ch)
开发者ID:drawingboardmedia,项目名称:django-smart-selects,代码行数:101,代码来源:widgets.py


示例18: render

 def render(self, name, value, attrs=None, choices=()):
     if len(name.split('-')) > 1:  # formset
         chain_field = '-'.join(name.split('-')[:-1] + [self.chain_field])
     else:
         chain_field = self.chain_field
     if not self.view_name:
         if self.show_all:
             view_name = 'chained_filter_all'
         else:
             view_name = 'chained_filter'
     else:
         view_name = self.view_name
     kwargs = {'app': self.app_name, 'model': self.model_name,
               'field': self.model_field, 'value': '1'}
     if self.manager is not None:
         kwargs.update({'manager': self.manager})
     url = URL_PREFIX + ('/'.join(reverse(view_name, kwargs=kwargs).split('/')[:-2]))
     # Hacky way to getting the correct empty_label from the field instead of a hardcoded '--------'
     empty_label = iter(self.choices).next()[1]
     data_div = '<div class="field-smart-select-data" style="display: none" data-chained-field="%s" data-url="%s" ' \
                'data-value="%s" data-auto-choose="%s" data-empty-label="%s" data-id="%s"></div>' \
                % (chain_field, url, value, self.auto_choose, empty_label, attrs['id'])
     final_choices = []
     if value:
         queryset = self.get_queryset(value)
         item = queryset.filter(pk=value)[0]
         try:
             pk = getattr(item, self.model_field + '_id')
             key_filter = {self.model_field: pk}
         except AttributeError:
             try:  # maybe m2m?
                 pks = getattr(item, self.model_field).all().values_list('pk', flat=True)
                 key_filter = {self.model_field + '__in': pks}
             except AttributeError:
                 try:  # maybe a set?
                     pks = getattr(item, self.model_field + '_set').all().values_list('pk', flat=True)
                     key_filter = {self.model_field + '__in': pks}
                 except Exception:   # give up
                     key_filter = {}
         filtered = list(queryset.filter(**key_filter).distinct())
         filtered.sort(cmp=locale.strcoll, key=lambda x: unicode_sorter(unicode(x)))
         for choice in filtered:
             final_choices.append((choice.pk, unicode(choice)))
     if len(final_choices) > 1:
         final_choices = [('', empty_label)] + final_choices
     if self.show_all:
         final_choices.append(('', empty_label))
         self.choices = list(self.choices)
         self.choices.sort(cmp=locale.strcoll, key=lambda x: unicode_sorter(x[1]))
         for ch in self.choices:
             if not ch in final_choices:
                 final_choices.append(ch)
     self.choices = []
     final_attrs = self.build_attrs(attrs, name=name)
     if 'class' in final_attrs:
         final_attrs['class'] += ' chained'
     else:
         final_attrs['class'] = 'chained'
     output = super(ChainedSelect, self).render(name, value, final_attrs, choices=final_choices)
     output += data_div
     return mark_safe(output)
开发者ID:emergence,项目名称:django-smart-selects,代码行数:61,代码来源:widgets.py


示例19: render


#.........这里部分代码省略.........
                    elem.value = chosenId;
                }
                fireEvent(elem, 'change');
                win.close();
            }

            $(document).ready(function(){
                function fill_field(val, init_value){
                    if (!val || val==''){
                        options = '<option value="">%(empty_label)s<'+'/option>';
                        $("#%(id)s").html(options);
                        $('#%(id)s option:first').attr('selected', 'selected');
                        $("#%(id)s").trigger('change');
                        return;
                    }
                    $.getJSON("%(url)s/"+val+"/", function(j){
                        var options = '<option value="">%(empty_label)s<'+'/option>';
                        for (var i = 0; i < j.length; i++) {
                            options += '<option value="' + j[i].value + '">' + j[i].display + '<'+'/option>';
                        }
                        var width = $("#%(id)s").outerWidth();
                        $("#%(id)s").html(options);
                        if (navigator.appVersion.indexOf("MSIE") != -1)
                            $("#%(id)s").width(width + 'px');
                   

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python CardMonitoring.CardMonitor类代码示例发布时间:2022-05-27
下一篇:
Python logger.warning函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap