コード例 #1
0
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')
コード例 #2
0
ファイル: views.py プロジェクト: AndreLobato/raizcidadanista
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')
コード例 #3
0
ファイル: views.py プロジェクト: pygaur/taxiforpool
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')
コード例 #4
0
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')
コード例 #5
0
ファイル: views.py プロジェクト: AndreLobato/raizcidadanista
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')
コード例 #6
0
ファイル: views.py プロジェクト: Anber/django-smart-selects
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')
コード例 #7
0
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")
コード例 #8
0
ファイル: views.py プロジェクト: Japje/django-smart-selects
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')
コード例 #9
0
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(key=lambda x: unicode_sorter(force_text(x)))
    final = []
    for item in results:
        final.append({'value': item.pk, 'display': force_text(item)})
    results = list(model_class._default_manager.exclude(**keywords))
    results.sort(key=lambda x: unicode_sorter(force_text(x)))
    final.append({'value': "", 'display': "---------"})

    for item in results:
        final.append({'value': item.pk, 'display': force_text(item)})
    json_ = json.dumps(final)
    return HttpResponse(json_, content_type='application/json')
コード例 #10
0
def filterchain_all(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)))
    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')
コード例 #11
0
ファイル: views.py プロジェクト: AndresDileva/ProyectoFinal
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')
コード例 #12
0
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')
コード例 #13
0
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")
コード例 #14
0
ファイル: views.py プロジェクト: kabucey/django-smart-selects
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')
コード例 #15
0
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 = simplejson.dumps(result)
    return HttpResponse(json, mimetype='application/json')
コード例 #16
0
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')
コード例 #17
0
ファイル: views.py プロジェクト: skotsjedal/caglol
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')
コード例 #18
0
 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)
コード例 #19
0
ファイル: widgets.py プロジェクト: anlaplante/mahana
    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)
コード例 #20
0
    def render(self,
               name,
               value,
               attrs=None,
               choices=(),
               renderer=None):  # noqa: C901
        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
        k1 = {
            "app": self.to_app_name,
            "model": self.to_model_name,
            "field": self.chained_model_field,
        }
        k2 = {
            "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.chained_child_app and self.chained_child_model and self.chained_child_field:
            k3 = {
                "child_app": self.chained_child_app,
                "child_model": self.chained_child_model,
                "child_field": self.chained_child_field,
            }
            kwargs = dict(k1, **k3, **k2)
        else:
            kwargs = dict(k1, **k2)

        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"
        if choices:
            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]
        else:
            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)
            if self.sort:
                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_choices

        attrs.update(self.attrs)
        attrs["data-chainfield"] = chained_field
        attrs["data-url"] = url
        attrs["data-value"] = "null" if value is None or value == "" else value
        attrs["data-auto_choose"] = auto_choose
        attrs["data-empty_label"] = escape(empty_label)
        attrs["name"] = name
        final_attrs = self.build_attrs(attrs)
        if "class" in final_attrs:
            final_attrs["class"] += " chained-fk"
        else:
            final_attrs["class"] = "chained-fk"

        if renderer:
            output = super(ChainedSelect, self).render(name, value,
                                                       final_attrs, renderer)
        else:
            output = super(ChainedSelect, self).render(name, value,
                                                       final_attrs)

        return mark_safe(output)
コード例 #21
0
    def render(self, name, value, attrs=None, choices=()):  # noqa: C901
        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'
        if choices:
            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]
        else:
            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)
            if self.sort:
                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_choices

        attrs.update(self.attrs)
        attrs["data-chainfield"] = chained_field
        attrs["data-url"] = url
        attrs["data-value"] = "null" if value is None or value == "" else value
        attrs["data-auto_choose"] = auto_choose
        attrs["data-empty_label"] = escape(empty_label)
        attrs["name"] = name
        final_attrs = self.build_attrs(attrs)
        if 'class' in final_attrs:
            final_attrs['class'] += ' chained-fk'
        else:
            final_attrs['class'] = 'chained-fk'

        output = super(ChainedSelect, self).render(name, value, final_attrs)

        return mark_safe(output)
コード例 #22
0
ファイル: widgets.py プロジェクト: acdha/django-smart-selects
    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 = ()
        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)
コード例 #23
0
    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]))
        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" src="/site_media/media/javascript/public/jquery-1.5.2.min.js"></script>
        <script type="text/javascript">
        //<![CDATA[
        // this is for accessing the fill_field globally
       
        (function($) {
            function fireEvent(element,event){
                if (document.createEventObject){
                // dispatch for IE
                var evt = document.createEventObject();
                return element.fireEvent('on'+event,evt)
                }
                else{
                // dispatch for firefox + others
                var evt = document.createEvent("HTMLEvents");
                evt.initEvent(event, true, true ); // event type,bubbling,cancelable
                return !element.dispatchEvent(evt);
                }
            };

            function dismissRelatedLookupPopup(win, chosenId) {
                var name = windowname_to_id(win.name);
                var elem = document.getElementById(name);
                if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
                    elem.value += ',' + chosenId;
                } else {
                    elem.value = chosenId;
                }
                fireEvent(elem, 'change');
                win.close();
            };
	    
            var fill_field = function(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;
                }
                $.ajaxSetup({async:false});
                $.getJSON("%(url)s/"+val+"/", function(j){
                    var selected_state_value = '%(value)s';
                    if (j.out == ''){
                        // convert select field into textfield if no state is assigned for selected country
                        // User can fill Custom value into state field
                        $("#%(id)s").replaceWith('<input id="%(id)s" type="text" name="%(name)s" value="" />');
                        document.getElementById("%(id)s").value = selected_state_value;
                        $('label[for="%(id)s"]').html(j.political_divisions);
                        selected_state_value = '';
                    }
                    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)
コード例 #24
0
    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,
            '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:
            empty_label = iterator.next(
            )[1]  # Hacky way to getting the correct empty_label from the field instead of a hardcoded '--------'
        js = """
        <script type="text/javascript">
        //<![CDATA[
        (function($) {
            function fireEvent(element,event){
                if (document.createEventObject){
                // dispatch for IE
                var evt = document.createEventObject();
                return element.fireEvent('on'+event,evt)
                }
                else{
                // dispatch for firefox + others
                var evt = document.createEvent("HTMLEvents");
                evt.initEvent(event, true, true ); // event type,bubbling,cancelable
                return !element.dispatchEvent(evt);
                }
            }

            function dismissRelatedLookupPopup(win, chosenId) {
                var name = windowname_to_id(win.name);
                var elem = document.getElementById(name);
                if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
                    elem.value += ',' + chosenId;
                } else {
                    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');
                        $('#%(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(!$("#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();
                    }
                }
            }
        })(jQuery || django.jQuery);
        //]]>
        </script>

        """
        js = js % {
            "chainfield": chain_field,
            "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)
コード例 #25
0
    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);
                chainedfk.init(chainfield+'_0', 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)
            if self.sort:
                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_choices

        final_attrs = self.build_attrs(attrs, name=name)
        if 'class' in final_attrs:
            final_attrs['class'] += ' chained'
        else:
            final_attrs['class'] = 'chained'

        output = js
        output += super(ChainedSelect, self).render(name, value, final_attrs)

        return mark_safe(output)
コード例 #26
0
 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)
コード例 #27
0
    def render(self, name, value, attrs=None, choices=()):
        chain_fields = self.chain_fields
        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,
        }
        if self.manager is not None:
            kwargs.update({'manager': self.manager})
        url = reverse(view_name, kwargs=kwargs)
        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($) {
            function fireEvent(element,event){
                if (document.createEventObject){
                // dispatch for IE
                var evt = document.createEventObject();
                return element.fireEvent('on'+event,evt)
                }
                else{
                // dispatch for firefox + others
                var evt = document.createEvent("HTMLEvents");
                evt.initEvent(event, true, true ); // event type,bubbling,cancelable
                return !element.dispatchEvent(evt);
                }
            }

            function dismissRelatedLookupPopup(win, chosenId) {
                var name = windowname_to_id(win.name);
                var elem = document.getElementById(name);
                if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
                    elem.value += ',' + chosenId;
                } else {
                    elem.value = chosenId;
                }
                fireEvent(elem, 'change');
                win.close();
            }

            $(document).ready(function(){
                var chainfields = $.parseJSON('%(chainfields_json)s');
                function fill_field(values, init_value){
                    $.each(values, function(model, val){
                        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", values, 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');
                        $('#%(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(!$("%(chainfields_ids)s").hasClass("chained")){
                    var values = {};
                    $.each(chainfields, function(field, model){
                        values[model] = $("#id_"+field).val();
                    });

                    fill_field(values, "%(value)s");
                }
                
                if($("%(chainfields_ids)s").hasClass('vForeignKeyRawIdAdminField')){
                    var ant = $("%(chainfields_ids)s").val();
                    var interval = setInterval(function(){
                      if($("%(chainfields_ids)s").val() != ant){
                        var start_value = $("#%(id)s").val();
                        var values = {};
                        $.each(chainfields, function(field, model){
                            values[model] = $("#id_"+field).val();
                        });
                        fill_field(values, start_value);

                        clearInterval(interval);
                      }
                    },500);

                }else{
                    $("%(chainfields_ids)s").change(function(){
                        var start_value = $("#%(id)s").val();
                        var values = {};
                        $.each(chainfields, function(field, model){
                            values[model] = $("#id_"+field).val();
                        });
                        fill_field(values, start_value);
                    })
                }
            })
            if (typeof(dismissAddAnotherPopup) !== 'undefined') {
                var oldDismissAddAnotherPopup = dismissAddAnotherPopup;
                dismissAddAnotherPopup = function(win, newId, newRepr) {
                    oldDismissAddAnotherPopup(win, newId, newRepr);
                    if (windowname_to_id(win.name) == "%(chainfields_ids)s") {
                        $("%(chainfields_ids)s").change();
                    }
                }
            }
        })(jQuery || django.jQuery);
        //]]>
        </script>

        """
        js = js % {
            "chainfields_ids":
            u','.join(['#id_%s' % field for field in chain_fields.keys()]),
            "chainfields_json":
            simplejson.dumps(chain_fields),
            "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]
            filter = {}
            for field, model_field in self.chain_fields.items():
                try:
                    pk = getattr(item, model_field + "_id")
                    filter[model_field] = pk
                except AttributeError:
                    try:  # maybe m2m?
                        pks = getattr(item,
                                      model_field).all().values_list('pk',
                                                                     flat=True)
                        filter[model_field + "__in"] = pks
                    except AttributeError:
                        try:  # maybe a set?
                            pks = getattr(item, model_field +
                                          "_set").all().values_list('pk',
                                                                    flat=True)
                            filter[model_field + "__in"] = pks
                        except:
                            pass

            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)
コード例 #28
0
    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,
            "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,
            "chain_field": self.chain_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]))
        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:
            empty_label = iterator.next()[
                1
            ]  # Hacky way to getting the correct empty_label from the field instead of a hardcoded '--------'
        js = """
        <script type="text/javascript">
        //<![CDATA[
        (function($) {
            function fireEvent(element,event){
                if (document.createEventObject){
                // dispatch for IE
                var evt = document.createEventObject();
                return element.fireEvent('on'+event,evt)
                }
                else{
                // dispatch for firefox + others
                var evt = document.createEvent("HTMLEvents");
                evt.initEvent(event, true, true ); // event type,bubbling,cancelable
                return !element.dispatchEvent(evt);
                }
            }

            function dismissRelatedLookupPopup(win, chosenId) {
                var name = windowname_to_id(win.name);
                var elem = document.getElementById(name);
                if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
                    elem.value += ',' + chosenId;
                } else {
                    elem.value = chosenId;
                }
                fireEvent(elem, 'change');
                win.close();
            }

            $(document).ready(function(){
                var el = $("#%(id)s");
                function fill_field(val, init_value, pk){
                    if ((!val || val=='') && !pk){
                        options = '<option value="">%(empty_label)s<'+'/option>';
                        $("#%(id)s").html(options);
                        $('#%(id)s option:first').attr('selected', 'selected');
                        $("#%(id)s").trigger('change');
                        return;
                    }
                    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)
コード例 #29
0
    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]))
        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($) {
            function fireEvent(element,event){
                if (document.createEventObject){
                // dispatch for IE
                var evt = document.createEventObject();
                return element.fireEvent('on'+event,evt)
                }
                else{
                // dispatch for firefox + others
                var evt = document.createEvent("HTMLEvents");
                evt.initEvent(event, true, true ); // event type,bubbling,cancelable
                return !element.dispatchEvent(evt);
                }
            }

            function dismissRelatedLookupPopup(win, chosenId) {
                var name = windowname_to_id(win.name);
                var elem = document.getElementById(name);
                if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
                    elem.value += ',' + chosenId;
                } else {
                    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 = '';
                       for (var i = 0; i < j.length; i++) {
                           options += '{' + 'text:"' + j[i].display + '", ' + 'value:' + j[i].value + '}';
                           if (i < j.length - 1){
                               options += ','
                           }
                           
                       }
                       
                       var json_data = '[' + options + ']';
                       
                       var obj = eval ("(" + json_data + ")");

                       
                       var selectize = $("#%(id)s")[0].selectize;
                       selectize.clear();
                       selectize.clearOptions();
                       selectize.load(function(callback) {
                           callback(obj);
                       });
                    })
                }

                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();
                    }
                }
            }
        })(jQuery || django.jQuery);
        //]]>
        </script>

        """
        js = js % {"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)
コード例 #30
0
    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:
            view_name = "chained_filter_all"
        else:
            view_name = "chained_filter"
        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 = "/".join(reverse(view_name, kwargs = kwargs).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($) {
            function fireEvent(element,event){
                if (document.createEventObject){
                // dispatch for IE
                var evt = document.createEventObject();
                return element.fireEvent('on'+event,evt)
                }
                else{
                // dispatch for firefox + others
                var evt = document.createEvent("HTMLEvents");
                evt.initEvent(event, true, true ); // event type,bubbling,cancelable
                return !element.dispatchEvent(evt);
                }
            }

            function dismissRelatedLookupPopup(win, chosenId) {
                var name = windowname_to_id(win.name);
                var elem = document.getElementById(name);
                if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
                    elem.value += ',' + chosenId;
                } else {
                    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');
                        $('#%(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(!$("#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();
                    }
                }
            }
        })(jQuery || django.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 = ()
        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)
コード例 #31
0
ファイル: widgets.py プロジェクト: blag/django-smart-selects
    def render(self, name, value, attrs=None, choices=()):  # noqa: C901
        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'
        if choices:
            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]
        else:
            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)
            if self.sort:
                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_choices

        attrs.update(self.attrs)
        attrs["data-chainfield"] = chained_field
        attrs["data-url"] = url
        attrs["data-value"] = "null" if value is None or value == "" else value
        attrs["data-auto_choose"] = auto_choose
        attrs["data-empty_label"] = escape(empty_label)
        attrs["name"] = name
        final_attrs = self.build_attrs(attrs)
        if 'class' in final_attrs:
            final_attrs['class'] += ' chained-fk'
        else:
            final_attrs['class'] = 'chained-fk'

        output = super(ChainedSelect, self).render(name, value, final_attrs)

        return mark_safe(output)