Example #1
0
def ajax_lookup(request,channel):

    """ this view supplies results for foreign keys and many to many fields """

    # it should come in as GET unless global $.ajaxSetup({type:"POST"}) has been set
    # in which case we'll support POST
    if request.method == "GET":
        # we could also insist on an ajax request
        if 'term' not in request.GET:
            return HttpResponse('')
        query = request.GET['term']
    else:
        if 'term' not in request.POST:
            return HttpResponse('') # suspicious
        query = request.POST['term']

    lookup = get_lookup(channel)
    if hasattr(lookup,'check_auth'):
        lookup.check_auth(request)

    if len(query) >= getattr(lookup, 'min_length', 1):
        instances = lookup.get_query(query,request)
    else:
        instances = []

    results = simplejson.dumps([
        {
            'pk': unicode(getattr(item,'pk',None)),
            'value': lookup.get_result(item),
            'match' : lookup.format_match(item),
            'repr': lookup.format_item_display(item)
        } for item in instances
    ])

    return HttpResponse(results, mimetype='application/javascript')
Example #2
0
def ajax_lookup(request,channel):
    """This view supplies results for both foreign keys and many to many fields.
    """
    def empty_response(): return HttpResponse('') # suspicious

    def render_selected(lookup_channel, item):
        itemf = lookup_channel.render_selected(item)
        itemf = itemf.replace("\n","").replace("|","¦")
        return itemf
    
    # Get and check the request.
    if request.method == "GET":
        request_by_method = request.GET
    elif request.method == "POST":
        request_by_method = request.POST
    else: return empty_response()    
    
    lookup_channel = get_lookup(channel)
    
    if 'q' in request_by_method:
        instances = lookup_channel.get_by_query(request_by_method['q'],request)
        results = []
        for item in instances:
            itemf = render_selected(lookup_channel, item)
            resultf = lookup_channel.render_dropdown_item(item)
            resultf = resultf.replace("\n","").replace("|","¦")
            results.append( "|".join((unicode(item.pk),itemf,resultf)) )
        return HttpResponse("\n".join(results))
    elif 'id' in request_by_method:
        instance = lookup_channel.get_by_pk(request_by_method['id'],request)
        return HttpResponse(render_selected(lookup_channel, instance))
    else:
        return empty_response()
Example #3
0
    def _clean_politician_set(self, cleaned_data, geoname_ids):
        """Return a representation of Politician objects based on 
        the data contained into an external API

        Check that the Total threshold come with the form is equal
        to the sum of politicians threshold deltas  """

        field_name = "politician_set"
        politician_ids = [int(elem) for elem in cleaned_data[field_name].strip("|").split("|")]
        politician_ids_copy = list(politician_ids)

        if politician_ids:

            for cityrep_id in geoname_ids:
                if not len(politician_ids_copy):
                    break
                found_ids = self.get_politicians_from_cityrep(politician_ids_copy, cityrep_id)
                # print("\n\nfound_ids: %s\n" % found_ids)
                for politician_id in found_ids:
                    politician_ids_copy.remove(politician_id)

            if len(politician_ids_copy):
                raise exceptions.ValidationError(
                    u"Non tutti i politici sono stati recuperati. Sono rimasti fuori i politici con id: %s"
                    % politician_ids_copy
                )

            lookup = get_lookup(MAP_FIELD_NAME_TO_CHANNEL[field_name])
            values = lookup.get_objects(politician_ids)

        else:
            values = []

        return values
Example #4
0
    def render(self, name, value, attrs=None):
        value = value or ""
        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop("id", name)

        lookup = get_lookup(self.channel)
        if value:
            objs = lookup.get_objects([value])
            try:
                obj = objs[0]
            except IndexError:
                raise Exception("%s cannot find object:%s" % (lookup, value))
            current_result = mark_safe(lookup.format_item(obj))
        else:
            current_result = ""
        context = {
            "name": name,
            "html_id": self.html_id,
            "lookup_url": reverse("ajax_lookup", kwargs={"channel": self.channel}),
            "current_id": value,
            "current_result": current_result,
            "help_text": self.help_text,
            "extra_attrs": mark_safe(flatatt(final_attrs)),
            "func_slug": self.html_id.replace("-", ""),
            "add_link": self.add_link,
            "admin_media_prefix": settings.ADMIN_MEDIA_PREFIX,
            "autocompleteParams": self.params,
        }

        return mark_safe(
            render_to_string(("newautocompleteselect_%s.html" % self.channel, "newautocompleteselect.html"), context)
        )
Example #5
0
def ajax_lookup(request, channel):

    """ this view supplies results for foreign keys and many to many fields """

    # it should come in as GET unless global $.ajaxSetup({type:"POST"}) has been set
    # in which case we'll support POST
    if request.method == "GET":
        # we could also insist on an ajax request
        if 'term' not in request.GET:
            return HttpResponse('')
        query = request.GET['term']
    else:
        if 'term' not in request.POST:
            return HttpResponse('')  # suspicious
        query = request.POST['term']

    lookup = get_lookup(channel)
    if hasattr(lookup, 'check_auth'):
        lookup.check_auth(request)

    if len(query) >= getattr(lookup, 'min_length', 1):
        instances = lookup.get_query(query, request)
    else:
        instances = []

    results = json.dumps([
        {
            'pk': force_text(getattr(item, 'pk', None)),
            'value': lookup.get_result(item),
            'match': lookup.format_match(item),
            'repr': lookup.format_item_display(item)
        } for item in instances
    ])

    return HttpResponse(results, mimetype='application/javascript')
Example #6
0
    def _clean_geoname_set(self, cleaned_data):
        """Return a representation of Geoname objects based on 
        the data contained into an external API"""
        # This is _clean method because it has to be called BEFORE _clean_politician_set

        geoname_ids = cleaned_data.get("geoname_set")

        if geoname_ids:
            field_name = "geoname_set"
            lookup = get_lookup(MAP_FIELD_NAME_TO_CHANNEL[field_name])
            values = lookup.get_objects(geoname_ids)

            if len(values) != len(geoname_ids):
                for value in values:
                    if value in geoname_ids:
                        values.remove(value)
                # raise exceptions.InvalidGeonameListError(values)
                raise exceptions.ValidationError(
                    u"Non tutti i luoghi sono stati recuperati. Sono rimasti fuori i luoghi con id: %s" % values
                )

        else:
            values = []

        return values
    def render(self, name, value, attrs=None):

        value = value or ""
        final_attrs = self.build_attrs(attrs, name=name)
        self.html_id = final_attrs.pop("pk", name)

        lookup = get_lookup(self.channel)
        if value:
            current_result = mark_safe(lookup.format_item(lookup.get_objects([value])[0]))
        else:
            current_result = ""

        context = {
            "name": name,
            "html_id": self.html_id,
            "lookup_url": reverse("ajax_lookup", kwargs={"channel": self.channel}),
            "current_id": value,
            "current_result": current_result,
            "help_text": self.help_text,
            "extra_attrs": mark_safe(flatatt(final_attrs)),
            "func_slug": self.html_id.replace("-", ""),
            "add_link": self.add_link,
            "admin_media_prefix": settings.ADMIN_MEDIA_PREFIX,
        }

        return mark_safe(
            render_to_string(("autocompleteselect_%s.html" % self.channel, "autocompleteselect.html"), context)
        )
    def render(self, name, value, attrs=None):

        initial = value or ''

        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)
        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = u''

        context = {
            'current_repr': initial,
            'current_id': initial,
            'help_text': help_text,
            'html_id': self.html_id,
            'name': name,
            'extra_attrs': mark_safe(flatatt(final_attrs)),
            'func_slug': self.html_id.replace("-",""),
        }
        context.update(plugin_options(lookup,self.channel,self.plugin_options,initial))
        context.update(bootstrap())

        templates = ('autocomplete_%s.html' % self.channel,
                     'autocomplete.html')
        return mark_safe(render_to_string(templates, context))
    def render(self, name, value, attrs=None):

        value = value or ''
        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)
        if value:
            objs = lookup.get_objects([value])
            try:
                obj = objs[0]
            except IndexError:
                raise Exception("%s cannot find object:%s" % (lookup, value))
            current_result = mark_safe(lookup.format_item(obj))
        else:
            current_result = ''

        context = {
            'name': name,
            'html_id': self.html_id,
            'lookup_url': reverse('ajax_lookup',
                                  kwargs={'channel': self.channel}),
            'current_id': value,
            'current_result': current_result,
            'help_text': self.help_text,
            'extra_attrs': mark_safe(flatatt(final_attrs)),
            'func_slug': self.html_id.replace("-", ""),
            'add_link': self.add_link,
            'admin_media_prefix': settings.ADMIN_MEDIA_PREFIX
        }

        return mark_safe(
            render_to_string(('autocompleteselect_%s.html' % self.channel,
                              'autocompleteselect.html'), context))
Example #10
0
    def render(self, name, value, attrs=None):

        initial = value or ''

        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)
        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = u''

        context = {
            'current_repr': initial,
            'current_id': initial,
            'help_text': help_text,
            'html_id': self.html_id,
            'name': name,
            'extra_attrs': mark_safe(flatatt(final_attrs)),
            'func_slug': self.html_id.replace("-",""),
        }
        context.update(plugin_options(lookup,self.channel,self.plugin_options,initial))
        context.update(bootstrap())

        templates = ('autocomplete_%s.html' % self.channel,
                     'autocomplete.html')
        return mark_safe(render_to_string(templates, context))
Example #11
0
	def render(self, name, value, attrs=None):
		value = value or ''
		final_attrs = self.build_attrs(attrs)
		self.html_id = final_attrs.pop('id', name)

		lookup = get_lookup(self.channel)
		if value:
		    objs = lookup.get_objects([value])
		    try:
		        obj = objs[0]
		    except IndexError:
		        raise Exception("%s cannot find object:%s" % (lookup, value))
		    current_result = mark_safe(lookup.format_item( obj ) )
		else:
		    current_result = ''
		context = {
		        'name': name,
		        'html_id' : self.html_id,
		        'lookup_url': reverse('ajax_lookup',kwargs={'channel':self.channel}),
		        'current_id': value,
		        'current_result': current_result,
		        'help_text': self.help_text,
		        'extra_attrs': mark_safe(flatatt(final_attrs)),
		        'func_slug': self.html_id.replace("-",""),
		        'add_link' : self.add_link,
		        'admin_media_prefix' : settings.ADMIN_MEDIA_PREFIX,
			'autocompleteParams' : self.params
		        }

		return mark_safe(render_to_string(('newautocompleteselect_%s.html' % self.channel, 'newautocompleteselect.html'),context))
Example #12
0
def ajax_lookup(request,channel):
    """ this view supplies results for both foreign keys and many to many fields """

    # it should come in as GET unless global $.ajaxSetup({type:"POST"}) has been set
    # in which case we'll support POST
    if request.method == "POST":
        if 'q' not in request.POST:
            return HttpResponse('') # suspicious
        query = request.POST['q']
    else:
        # we could also insist on an ajax request
        if 'q' not in request.GET:
            return HttpResponse('')
        query = request.GET['q']
    
    lookup_channel = get_lookup(channel)
    
    if query:
        instances = lookup_channel.get_query(query, request)
    else:
        instances = []

    results = []
    for item in instances:
        itemf = lookup_channel.format_item(item)
        itemf = itemf.replace("\n", "").replace("|", "¦")
        resultf = lookup_channel.format_result(item)
        resultf = resultf.replace("\n", "").replace("|", "¦")
        results.append( "|".join((unicode(item.pk), itemf, resultf)) )
    return HttpResponse("\n".join(results))
Example #13
0
    def render(self, name, value, attrs=None):

        value = value or ''
        final_attrs = self.build_attrs(attrs,  name=name)
        self.html_id = final_attrs.pop('pk', name)

        lookup = get_lookup(self.channel)
        if value:
            current_result = mark_safe(lookup.format_result( lookup.get_objects([value])[0] ))
        else:
            current_result = ''

        context = {
                'name': name,
                'html_id' : self.html_id,
                'lookup_url': reverse('ajax_lookup',kwargs={'channel':self.channel}),
                'current_id': value,
                'current_result': current_result,
                'help_text': self.help_text,
                'extra_attrs': mark_safe(flatatt(final_attrs)),
                'func_slug': self.html_id.replace("-",""),
                'add_link' : self.add_link,
                'admin_media_prefix' : settings.ADMIN_MEDIA_PREFIX
                }

        return mark_safe(render_to_string(('autocompleteselect_%s.html' % self.channel, 'autocompleteselect.html'),context))
Example #14
0
    def render(self, name, value, attrs=None):

        value = value or ''
        
        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)

        context = {
            'current_repr': mark_safe("'%s'" % escapejs(value)),
            'current_id': value,
            'help_text': self.help_text,
            'html_id': self.html_id,
            'min_length': getattr(lookup, 'min_length', 1),
            'lookup_url': reverse('ajax_lookup', args=[self.channel]),
            'name': name,
            'extra_attrs':mark_safe(flatatt(final_attrs)),
            'func_slug': self.html_id.replace("-",""),
        }
        context.update(bootstrap())

        templates = ('autocomplete_%s.html' % self.channel,
                     'autocomplete.html')
        return mark_safe(render_to_string(templates, context))
Example #15
0
    def render(self, name, value, attrs=None):

        value = value or ''
        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)
        if value:
            objs = lookup.get_objects([value])
            try:
                obj = objs[0]
            except IndexError:
                raise Exception("%s cannot find object:%s" % (lookup, value))
            display = lookup.format_item_display(obj)
            current_repr = mark_safe( """new Array("%s",%s)""" % (escapejs(display),obj.pk) )
        else:
            current_repr = 'null'

        context = {
                'name': name,
                'html_id' : self.html_id,
                'min_length': getattr(lookup, 'min_length', 1),
                'lookup_url': reverse('ajax_lookup',kwargs={'channel':self.channel}),
                'current_id': value,
                'current_repr': current_repr,
                'help_text': self.help_text,
                'extra_attrs': mark_safe(flatatt(final_attrs)),
                'func_slug': self.html_id.replace("-",""),
                'add_link' : self.add_link,
                }
        context.update(bootstrap())
        
        return mark_safe(render_to_string(('autocompleteselect_%s.html' % self.channel, 'autocompleteselect.html'),context))
Example #16
0
    def render(self, name, value, attrs=None):

        initial = value or ""

        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop("id", name)

        lookup = get_lookup(self.channel)
        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = u""

        context = {
            "current_repr": initial,
            "current_id": initial,
            "help_text": help_text,
            "html_id": self.html_id,
            "name": name,
            "extra_attrs": mark_safe(flatatt(final_attrs)),
            "func_slug": self.html_id.replace("-", ""),
        }
        context.update(plugin_options(lookup, self.channel, self.plugin_options, initial))
        context.update(bootstrap())

        templates = ("autocomplete_%s.html" % self.channel, "autocomplete.html")
        return mark_safe(render_to_string(templates, context))
Example #17
0
def ajax_lookup(request, channel):
    """ this view supplies results for both foreign keys and many to many fields """

    # it should come in as GET unless global $.ajaxSetup({type:"POST"}) has been set
    # in which case we'll support POST
    query_param = "term"
    if request.method == "GET":
        # we could also insist on an ajax request
        if query_param not in request.GET:
            return HttpResponse('')
        query = request.GET[query_param]
    else:
        if query_param not in request.POST:
            return HttpResponse('')
        query = request.POST[query_param]

    lookup_channel = get_lookup(channel)

    instances = lookup_channel.get_query(query, request)

    results = []
    for item in instances:
        itemf = lookup_channel.format_item(item)
        resultf = lookup_channel.format_result(item)
        result = {"pk": unicode(item.pk),
                  "value": itemf,
                  "label": resultf,
                  }
        autofill  = lookup_channel.generate_autofill(item)
        if autofill:
            result.update({"autofill": autofill})
        results.append(result)
    return HttpResponse(DjangoJSONEncoder().encode(results))
Example #18
0
    def _clean_geoname_set(self, cleaned_data):
        """Return a representation of Geoname objects based on 
        the data contained into an external API"""
        #This is _clean method because it has to be called BEFORE _clean_politician_set

        geoname_ids = cleaned_data.get('geoname_set')

        if geoname_ids:
            field_name = 'geoname_set'
            lookup = get_lookup(MAP_FIELD_NAME_TO_CHANNEL[field_name])
            values = lookup.get_objects(geoname_ids)

            if len(values) != len(geoname_ids):
                for value in values:
                    if value in geoname_ids:
                        values.remove(value)
                #raise exceptions.InvalidGeonameListError(values)
                raise exceptions.ValidationError(
                    u"Non tutti i luoghi sono stati recuperati. Sono rimasti fuori i luoghi con id: %s"
                    % values)

        else:
            values = []

        return values
Example #19
0
    def render(self, name, value, attrs=None):

        value = value or ''
        
        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)
        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = ''

        lookup_url = reverse('ajax_lookup',kwargs={'channel':self.channel})
        lookup_params = urllib.urlencode(self.extra_params_url)
        if lookup_params:
            lookup_url += '?%s' % lookup_params

        context = {
            'current_repr': value,
            'current_id': value,
            'help_text': help_text,
            'html_id': self.html_id,
            'min_length': getattr(lookup, 'min_length', 1),
            'lookup_url': lookup_url,
            'name': name,
            'extra_attrs':mark_safe(flatatt(final_attrs)),
            'func_slug': self.html_id.replace("-",""),
        }
        context.update(bootstrap())
        context.update(self.extra_context)
        templates = ('autocomplete_%s.html' % self.channel,
                     'autocomplete.html')
        return mark_safe(render_to_string(templates, context))
Example #20
0
    def render(self, name, value, attrs=None):

        value = value or ''
        
        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)
        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = ''
        context = {
            'current_repr': value,
            'current_id': value,
            'help_text': help_text,
            'html_id': self.html_id,
            'min_length': getattr(lookup, 'min_length', 1),
            'lookup_url': reverse('ajax_lookup', args=[self.channel]),
            'name': name,
            'extra_attrs':mark_safe(flatatt(final_attrs)),
            'func_slug': self.html_id.replace("-",""),
        }
        context.update(bootstrap())

        templates = ('autocomplete_%s.html' % self.channel,
                     'autocomplete.html')
        return mark_safe(render_to_string(templates, context))
Example #21
0
def ajax_lookup(request, channel):
    """ this view supplies results for both foreign keys and many to many fields """

    # it should come in as GET unless global $.ajaxSetup({type:"POST"}) has been set
    # in which case we'll support POST
    if request.method == "GET":
        # we could also insist on an ajax request
        if 'q' not in request.GET:
            return HttpResponse('')
        query = request.GET['q']
    else:
        if 'q' not in request.POST:
            return HttpResponse('')  # suspicious
        query = request.POST['q']

    lookup_channel = get_lookup(channel)

    if query:
        instances = lookup_channel.get_query(query, request)
    else:
        instances = []

    results = []
    for item in instances:
        itemf = lookup_channel.format_item(item)
        itemf = itemf.replace("\n", "").replace("|", "|")
        resultf = lookup_channel.format_result(item)
        resultf = resultf.replace("\n", "").replace("|", "|")
        results.append("|".join((unicode(item.pk), itemf, resultf)))
    return HttpResponse("\n".join(results))
Example #22
0
def ajax_lookup(request, channel):
    """ this view supplies results for both foreign keys and many to many fields """

    # it should come in as GET unless global $.ajaxSetup({type:"POST"}) has been set
    # in which case we'll support POST
    if request.method == "GET":
        # we could also insist on an ajax request
        if 'term' not in request.GET:
            return HttpResponse('')
        query = request.GET['term']
    else:
        if 'term' not in request.POST:
            return HttpResponse('')  # suspicious
        query = request.POST['term']

    lookup_channel = get_lookup(channel)
    if query:
        instances = lookup_channel.get_query(query, request)
    else:
        instances = []

    results = []
    for item in instances:
        label = lookup_channel.format_result(item)
        value = lookup_channel.format_item(item)
        results.append({
            "id": unicode(item.pk),
            "label": label,
            "value": value,
        })

    body = simplejson.dumps(results, indent=4)
    content_type = "application/json"
    return HttpResponse(body, content_type=content_type, status=200)
Example #23
0
    def render(self, name, value, attrs=None):

        value = value or ""

        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop("id", name)

        lookup = get_lookup(self.channel)
        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = ""
        context = {
            "current_repr": value,
            "current_id": value,
            "help_text": help_text,
            "html_id": self.html_id,
            "min_length": getattr(lookup, "min_length", 1),
            "lookup_url": reverse("ajax_lookup", args=[self.channel]),
            "name": name,
            "extra_attrs": mark_safe(flatatt(final_attrs)),
            "func_slug": self.html_id.replace("-", ""),
        }
        context.update(bootstrap())

        templates = ("autocomplete_%s.html" % self.channel, "autocomplete.html")
        return mark_safe(render_to_string(templates, context))
Example #24
0
    def render(self, name, value, attrs=None):
        attrs['class'] = attrs.get('class') or ''
        attrs['class'] += ' autocomplete_text'
        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)
        value = value or []
        return mark_safe(
            render_to_string(
                ('autocompleteselectmultiple_%s.html' % self.channel,
                 'autocompleteselectmultiple.html'), {
                     'name':
                     name,
                     'html_id':
                     self.html_id,
                     'lookup_url':
                     reverse('ajax_lookup', kwargs={'channel': self.channel}),
                     'current':
                     value,
                     'current_reprs':
                     mark_safe(
                         dumps([[obj.pk, lookup.format_item(obj)]
                                for obj in lookup.get_objects(value)])),
                     'help_text':
                     self.help_text if self.show_help_text else '',
                     'extra_attrs':
                     mark_safe(flatatt(final_attrs)),
                     'func_slug':
                     self.html_id.replace("-", ""),
                     'admin_media_prefix':
                     settings.ADMIN_MEDIA_PREFIX,
                     'unique_id':
                     'autocomplete-select-%s' % random.randint(0, 99999)
                 }))
Example #25
0
    def render(self, name, value, attrs=None):

        if value is None:
            value = []

        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)

        # eg. value = [3002L, 1194L]
        if value:
            current_ids = "|" + "|".join(
                str(pk) for pk in value) + "|"  # |pk|pk| of current
        else:
            current_ids = "|"

        objects = lookup.get_objects(value)

        # text repr of currently selected items
        initial = []
        for obj in objects:
            url = lookup.get_item_url(obj)
            item_display = lookup.format_item_display(obj)
            if url:
                display = '<a href="{}" target="_blank">{}</a>'.format(
                    url,
                    item_display,
                )
            else:
                display = item_display
            initial.append([display, obj.pk])

        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = u''

        context = {
            'name': name,
            'html_id': self.html_id,
            'current': value,
            'current_ids': current_ids,
            'current_reprs': mark_safe(simplejson.dumps(initial)),
            'help_text': help_text,
            'extra_attrs': mark_safe(flatatt(final_attrs)),
            'func_slug': self.html_id.replace("-", ""),
            'add_link': self.add_link,
        }
        context.update(
            plugin_options(lookup, self.channel, self.plugin_options, initial))
        context.update(bootstrap())

        return mark_safe(
            render_to_string(
                ('autocompleteselectmultiple_%s.html' % self.channel[1],
                 'autocompleteselectmultiple.html'), context))
Example #26
0
def deep_field_value(f):
    """Similar to *field_value* filter, but shows related object instead of
    foreign key"""
    field_value = f.field.to_python(f.value())
    if field_value != "" and isinstance(f.field, AutoCompleteSelectField):
        lookup = get_lookup(f.field.channel)
        found = lookup.get_objects([field_value])
        if found:
            field_value = found[0]
    return field_value
Example #27
0
def deep_field_value(f):
    """Similar to *field_value* filter, but shows related object instead of
    foreign key"""
    field_value = f.field.to_python(f.value())
    if field_value != '' and isinstance(f.field, AutoCompleteSelectField):
        lookup = get_lookup(f.field.channel)
        found = lookup.get_objects([field_value])
        if found:
            field_value = found[0]
    return field_value
Example #28
0
    def get_or_create_geonames(self, geoname_list):
        """ Here we have to check if there exist Geonames with pk into
        the provided ids.

        If there are ids that do not match with any of the existing Geoname
        pk, than create new Geonames togheter with their ExternalResource. 
        If there are some existing ExternalResource which was created too time 
        ago, then check the openpolis API to see if there had been some changes.
        """

        geonames = []
        lookup = get_lookup(MAP_FIELD_NAME_TO_CHANNEL['geoname_set'])

        for datum in geoname_list:

            #print("\ndatum: %s" % json_datum)
            ext_res_id = datum['id']
            ext_res_type = datum['location_type']['name']

            try:
                geoname = Geoname.objects.get(
                    external_resource__ext_res_id=ext_res_id,
                    external_resource__ext_res_type=ext_res_type
                )
            except Geoname.DoesNotExist as e:
                name = datum['name']
                kind = ext_res_type

                e_r = ExternalResource.objects.create(
                    ext_res_id = ext_res_id, 
                    ext_res_type = ext_res_type,
                    backend_name = lookup.get_backend_name(),
                )
                geoname = Geoname.objects.create(
                    name = name,
                    kind = kind,
                    external_resource = e_r
                )
                #TO REMOVE: just for testing purposes
                #geoname.external_resource.update_external_data(
                #    lookup,
                #    ext_res_id,
                #    datum
                #)

            else:
                last_get_delta = datetime.datetime.now() - geoname.external_resource.last_get_on
                if last_get_delta.seconds > Geoname.MAX_CACHE_VALID_MINUTES:
                    #TODO Matteo:
                    geoname.external_resource.update_external_data(datum)

            geonames.append(geoname)

        return geonames
Example #29
0
 def clean(self, value):
     if value:
         lookup = get_lookup(self.channel)
         objs = lookup.get_objects([value])
         if len(objs) != 1:
             raise forms.ValidationError(u"%s cannot find object: %s" % (lookup,value))
         return objs[0]
     else:
         if self.required:
             raise forms.ValidationError(self.error_messages['required'])
         return None
Example #30
0
 def value_from_datadict(self, data, files, name):
     got = data.get(name, None)
     if got != None:
         lookup = get_lookup(self.channel)
         if hasattr(lookup, 'value_from_data') and callable(
                 lookup.value_from_data):
             return lookup.value_from_data(got)
         else:
             return long(got)
     else:
         return None
Example #31
0
 def value_from_datadict(self, data, files, name):
     lookup = get_lookup(self.channel)
     added_val = getattr(lookup, 'auto_add', False) and data.get(
         "%s[added]" % name, None)
     if added_val:
         added_obj = lookup.create_from_ajax_string(ajax_string=added_val,
                                                    request_data=data,
                                                    form_field_name=name)
         return added_obj.pk
     else:
         return long(data.get(name, 0)) or None
    def render(self, name, value, attrs=None):

        if value is None:
            value = []

        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)

        current_name = ""  # the text field starts empty
        # eg. value = [3002L, 1194L]
        if value:
            current_ids = "|" + "|".join(
                str(pk) for pk in value) + "|"  # |pk|pk| of current
        else:
            current_ids = "|"

        objects = lookup.get_objects(value)

        # text repr of currently selected items
        current_repr_json = []
        for obj in objects:
            repr = lookup.format_item(obj)
            current_repr_json.append("""new Array("%s",%s)""" %
                                     (escapejs(repr), obj.pk))

        current_reprs = mark_safe("new Array(%s)" %
                                  ",".join(current_repr_json))
        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = ''

        context = {
            'name': name,
            'html_id': self.html_id,
            'lookup_url': reverse('ajax_lookup',
                                  kwargs={'channel': self.channel}),
            'current': value,
            'current_name': current_name,
            'current_ids': current_ids,
            'current_reprs': current_reprs,
            'help_text': help_text,
            'extra_attrs': mark_safe(flatatt(final_attrs)),
            'func_slug': self.html_id.replace("-", ""),
            'add_link': self.add_link,
            'admin_media_prefix': settings.ADMIN_MEDIA_PREFIX
        }
        return mark_safe(
            render_to_string(
                ('autocompleteselectmultiple_%s.html' % self.channel,
                 'autocompleteselectmultiple.html'), context))
Example #33
0
 def value_from_datadict(self, data, files, name):
     lookup = get_lookup(self.channel)
     added_val = getattr(lookup, 'auto_add', False) and data.get("%s[added]" % name, None)
     if added_val:
         added_obj = lookup.create_from_ajax_string(
             ajax_string=added_val,
             request_data=data,
             form_field_name=name
         )
         return added_obj.pk
     else:
         return long(data.get(name, 0)) or None
Example #34
0
 def clean(self, value):
     if value:
         lookup = get_lookup(self.channel)
         objs = lookup.get_objects([value])
         if len(objs) != 1:
             raise forms.ValidationError(u"%s cannot find object: %s" %
                                         (lookup, value))
         return objs[0]
     else:
         if self.required:
             raise forms.ValidationError(self.error_messages['required'])
         return None
Example #35
0
    def get_or_create_politicians(self, politician_list):
        """ Here we have to check if there exist Politician objects with pk into
        the provided ids.

        If there are ids that do not match with any of the existing Politician
        pks, than create new Geonames togheter with their ExternalResource. 
        If there are some existing ExternalResource which was created too time 
        ago, then check the openpolis API to see if there had been some changes.
        """

        politicians = []
        lookup = get_lookup(MAP_FIELD_NAME_TO_CHANNEL['politician_set'])

        for datum in politician_list:

            ext_res_id = datum['content_id']
            ext_res_type = datum['institution_charges']['current'][0]['charge_type']

            try:
                politician = Politician.objects.get(
                    external_resource__ext_res_id=ext_res_id,
                    external_resource__ext_res_type=ext_res_type
                )
            except Politician.DoesNotExist as e:

                first_name = datum['first_name']
                last_name = datum['last_name']
                charge = ext_res_type

                e_r = ExternalResource.objects.create(
                    ext_res_id = ext_res_id, 
                    ext_res_type = ext_res_type,
                    backend_name = lookup.get_backend_name(),
                    # MANCA IL DATA! TODO Matteo: valutare
                )
                politician = Politician.objects.create(
                    first_name=first_name,
                    last_name=last_name,
                    external_resource = e_r
                )

            else:
                last_get_delta = datetime.datetime.now() - politician.external_resource.last_get_on
                if last_get_delta.seconds > Politician.MAX_CACHE_VALID_MINUTES:
                    politician.external_resource.update_external_data(
                        lookup,
                        ext_res_id,
                        datum
                    )

            politicians.append(politician)

        return politicians
Example #36
0
def _check_can_add(self,user,model):
    """ check if the user can add the model, deferring first to the channel if it implements can_add() \
        else using django's default perm check. \
        if it can add, then enable the widget to show the + link """
    lookup = get_lookup(self.channel)
    try:
        can_add = lookup.can_add(user,model)
    except AttributeError:
        ctype = ContentType.objects.get_for_model(model)
        can_add = user.has_perm("%s.view_%s" % (ctype.app_label,ctype.model))
    if can_add:
        self.widget.add_link = reverse('add_popup',kwargs={'app_label':model._meta.app_label,'model':model._meta.object_name.lower()})
    def render(self, name, value, attrs=None):

        if value is None:
            value = []

        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)

        # eg. value = [3002L, 1194L]
        if value:
            current_ids = "|" + "|".join(
                str(pk) for pk in value) + "|"  # |pk|pk| of current
        else:
            current_ids = "|"

        objects = lookup.get_objects(value)

        # text repr of currently selected items
        current_repr_json = []
        for obj in objects:
            display = lookup.format_item_display(obj)
            current_repr_json.append("""new Array("%s",%s)""" %
                                     (escapejs(display), obj.pk))
        current_reprs = mark_safe("new Array(%s)" %
                                  ",".join(current_repr_json))

        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = ''

        context = {
            'name': name,
            'html_id': self.html_id,
            'min_length': getattr(lookup, 'min_length', 1),
            'lookup_url': reverse('ajax_lookup',
                                  kwargs={'channel': self.channel}),
            'current': value,
            'current_ids': current_ids,
            'current_reprs': current_reprs,
            'help_text': help_text,
            'extra_attrs': mark_safe(flatatt(final_attrs)),
            'func_slug': self.html_id.replace("-", ""),
            'add_link': self.add_link,
        }
        context.update(bootstrap())

        return mark_safe(
            render_to_string(
                ('autocompleteselectmultiple_%s.html' % self.channel,
                 'autocompleteselectmultiple.html'), context))
Example #38
0
    def get_or_create_geonames(self, geoname_list):
        """ Here we have to check if there exist Geonames with pk into
        the provided ids.

        If there are ids that do not match with any of the existing Geoname
        pk, than create new Geonames togheter with their ExternalResource. 
        If there are some existing ExternalResource which was created too time 
        ago, then check the openpolis API to see if there had been some changes.
        """

        geonames = []
        lookup = get_lookup(MAP_FIELD_NAME_TO_CHANNEL['geoname_set'])

        for datum in geoname_list:

            #print("\ndatum: %s" % json_datum)
            ext_res_id = datum['id']
            ext_res_type = datum['location_type']['name']

            try:
                geoname = Geoname.objects.get(
                    external_resource__ext_res_id=ext_res_id,
                    external_resource__ext_res_type=ext_res_type)
            except Geoname.DoesNotExist as e:
                name = datum['name']
                kind = ext_res_type

                e_r = ExternalResource.objects.create(
                    ext_res_id=ext_res_id,
                    ext_res_type=ext_res_type,
                    backend_name=lookup.get_backend_name(),
                )
                geoname = Geoname.objects.create(name=name,
                                                 kind=kind,
                                                 external_resource=e_r)
                #TO REMOVE: just for testing purposes
                #geoname.external_resource.update_external_data(
                #    lookup,
                #    ext_res_id,
                #    datum
                #)

            else:
                last_get_delta = datetime.datetime.now(
                ) - geoname.external_resource.last_get_on
                if last_get_delta.seconds > Geoname.MAX_CACHE_VALID_MINUTES:
                    #TODO Matteo:
                    geoname.external_resource.update_external_data(datum)

            geonames.append(geoname)

        return geonames
Example #39
0
    def render(self, name, value, attrs=None):

        if value is None:
            value = []

        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)

        # eg. value = [3002L, 1194L]
        if value:
            current_ids = "|" + "|".join( str(pk) for pk in value ) + "|" # |pk|pk| of current
        else:
            current_ids = "|"

        objects = lookup.get_objects(value)

        # text repr of currently selected items
        current_repr_json = []
        for obj in objects:
            display = lookup.format_item_display(obj)
            current_repr_json.append( """new Array("%s",%s)""" % (escapejs(display),obj.pk) )
        current_reprs = mark_safe("new Array(%s)" % ",".join(current_repr_json))
        
        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = ''

        lookup_url = reverse('ajax_lookup',kwargs={'channel':self.channel})
        lookup_params = urllib.urlencode(self.extra_params_url)
        if lookup_params:
            lookup_url += '?%s' % lookup_params
        context = {
            'name':name,
            'html_id':self.html_id,
            'min_length': getattr(lookup, 'min_length', 1),
            'lookup_url': lookup_url,
            'current':value,
            'current_ids':current_ids,
            'current_reprs': current_reprs,
            'help_text':help_text,
            'extra_attrs': mark_safe(flatatt(final_attrs)),
            'func_slug': self.html_id.replace("-",""),
            'add_link' : self.add_link,
        }
        context.update(bootstrap())
        context.update(self.extra_context)

        return mark_safe(render_to_string(('autocompleteselectmultiple_%s.html' % self.channel, 'autocompleteselectmultiple.html'),context))
    def render(self, name, value, attrs=None):

        if value is None:
            value = []

        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)

        # eg. value = [3002L, 1194L]
        if value:
            current_ids = "|" + "|".join( str(pk) for pk in value ) + "|" # |pk|pk| of current
        else:
            current_ids = "|"

        objects = lookup.get_objects(value)

        # text repr of currently selected items
        initial = []
        for obj in objects:
            url = lookup.get_item_url(obj)
            item_display = lookup.format_item_display(obj)
            if url:
                display = '<a href="{}" target="_blank">{}</a>'.format(
                    url, item_display,
                )
            else:
                display = item_display
            initial.append([display,obj.pk])

        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = u''

        context = {
            'name':name,
            'html_id':self.html_id,
            'current':value,
            'current_ids':current_ids,
            'current_reprs':mark_safe(simplejson.dumps(initial)),
            'help_text':help_text,
            'extra_attrs': mark_safe(flatatt(final_attrs)),
            'func_slug': self.html_id.replace("-",""),
            'add_link' : self.add_link,
        }
        context.update(plugin_options(lookup,self.channel,self.plugin_options,initial))
        context.update(bootstrap())

        return mark_safe(render_to_string(('autocompleteselectmultiple_%s.html' % self.channel[1], 'autocompleteselectmultiple.html'),context))
Example #41
0
    def render(self, name, value, attrs=None):

        if value is None:
            value = []

        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop("id", name)

        lookup = get_lookup(self.channel)

        # eg. value = [3002L, 1194L]
        if value:
            current_ids = "|" + "|".join(str(pk) for pk in value) + "|"  # |pk|pk| of current
        else:
            current_ids = "|"

        objects = lookup.get_objects(value)

        # text repr of currently selected items
        current_repr_json = []
        for obj in objects:
            display = lookup.format_item_display(obj)
            current_repr_json.append("""new Array("%s",%s)""" % (escapejs(display), obj.pk))
        current_reprs = mark_safe("new Array(%s)" % ",".join(current_repr_json))

        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = ""

        context = {
            "name": name,
            "html_id": self.html_id,
            "min_length": getattr(lookup, "min_length", 1),
            "lookup_url": reverse("ajax_lookup", kwargs={"channel": self.channel}),
            "current": value,
            "current_ids": current_ids,
            "current_reprs": current_reprs,
            "help_text": help_text,
            "extra_attrs": mark_safe(flatatt(final_attrs)),
            "func_slug": self.html_id.replace("-", ""),
            "add_link": self.add_link,
        }
        context.update(bootstrap())

        return mark_safe(
            render_to_string(
                ("autocompleteselectmultiple_%s.html" % self.channel, "autocompleteselectmultiple.html"), context
            )
        )
Example #42
0
def _check_can_add(self, user, model):
    """ check if the user can add the model, deferring first to
        the channel if it implements can_add()
        else using django's default perm check.
        if it can add, then enable the widget to show the + link
    """
    lookup = get_lookup(self.channel)
    if hasattr(lookup, 'can_add'):
        can_add = lookup.can_add(user, model)
    else:
        ctype = ContentType.objects.get_for_model(model)
        can_add = user.has_perm("%s.add_%s" % (ctype.app_label, ctype.model))
    if can_add:
        self.widget.add_link = reverse('add_popup', kwargs={'app_label': model._meta.app_label, 'model': model._meta.object_name.lower()})
Example #43
0
    def render(self, name, value, attrs=None):

        if value is None:
            value = []

        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop("id", name)

        lookup = get_lookup(self.channel)

        current_name = ""  # the text field starts empty
        # eg. value = [3002L, 1194L]
        if value:
            current_ids = "|" + "|".join(str(pk) for pk in value) + "|"  # |pk|pk| of current
        else:
            current_ids = "|"

        objects = lookup.get_objects(value)

        # text repr of currently selected items
        current_repr_json = []
        for obj in objects:
            repr = lookup.format_item(obj)
            current_repr_json.append("""new Array("%s",%s)""" % (escapejs(repr), obj.pk))

        current_reprs = mark_safe("new Array(%s)" % ",".join(current_repr_json))
        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = ""

        context = {
            "name": name,
            "html_id": self.html_id,
            "lookup_url": reverse("ajax_lookup", kwargs={"channel": self.channel}),
            "current": value,
            "current_name": current_name,
            "current_ids": current_ids,
            "current_reprs": current_reprs,
            "help_text": help_text,
            "extra_attrs": mark_safe(flatatt(final_attrs)),
            "func_slug": self.html_id.replace("-", ""),
            "add_link": self.add_link,
            "admin_media_prefix": settings.ADMIN_MEDIA_PREFIX,
        }
        return mark_safe(
            render_to_string(
                ("autocompleteselectmultiple_%s.html" % self.channel, "autocompleteselectmultiple.html"), context
            )
        )
Example #44
0
 def clean(self, value):
     if value:
         lookup = get_lookup(self.channel)
         objs = lookup.get_objects( [ value] )
         if len(objs) != 1:
             # someone else might have deleted it while you were editing
             # or your channel is faulty
             # out of the scope of this field to do anything more than tell you it doesn't exist
             raise forms.ValidationError(u"%s cannot find object: %s" % (lookup,value))
         return objs[0]
     else:
         if self.required:
             raise forms.ValidationError(self.error_messages['required'])
         return None
Example #45
0
 def clean(self, value):
     if value:
         lookup = get_lookup(self.channel)
         objs = lookup.get_objects( [ value] )
         if len(objs) != 1:
             # someone else might have deleted it while you were editing
             # or your channel is faulty
             # out of the scope of this field to do anything more than tell you it doesn't exist
             raise forms.ValidationError(u"%s cannot find object: %s" % (lookup,value))
         return objs[0]
     else:
         if self.required:
             raise forms.ValidationError(self.error_messages['required'])
         return None
Example #46
0
    def get_or_create_politicians(self, politician_list):
        """ Here we have to check if there exist Politician objects with pk into
        the provided ids.

        If there are ids that do not match with any of the existing Politician
        pks, than create new Geonames togheter with their ExternalResource. 
        If there are some existing ExternalResource which was created too time 
        ago, then check the openpolis API to see if there had been some changes.
        """

        politicians = []
        lookup = get_lookup(MAP_FIELD_NAME_TO_CHANNEL['politician_set'])

        for datum in politician_list:

            ext_res_id = datum['content_id']
            ext_res_type = datum['institution_charges']['current'][0][
                'charge_type']

            try:
                politician = Politician.objects.get(
                    external_resource__ext_res_id=ext_res_id,
                    external_resource__ext_res_type=ext_res_type)
            except Politician.DoesNotExist as e:

                first_name = datum['first_name']
                last_name = datum['last_name']
                charge = ext_res_type

                e_r = ExternalResource.objects.create(
                    ext_res_id=ext_res_id,
                    ext_res_type=ext_res_type,
                    backend_name=lookup.get_backend_name(),
                    # MANCA IL DATA! TODO Matteo: valutare
                )
                politician = Politician.objects.create(first_name=first_name,
                                                       last_name=last_name,
                                                       external_resource=e_r)

            else:
                last_get_delta = datetime.datetime.now(
                ) - politician.external_resource.last_get_on
                if last_get_delta.seconds > Politician.MAX_CACHE_VALID_MINUTES:
                    politician.external_resource.update_external_data(
                        lookup, ext_res_id, datum)

            politicians.append(politician)

        return politicians
Example #47
0
    def render(self, name, value, attrs=None):

        if value is None:
            value = []

        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop("id", name)

        lookup = get_lookup(self.channel)

        # eg. value = [3002L, 1194L]
        if value:
            current_ids = "|".join(str(pk) for pk in value)  # |pk|pk| of current
        else:
            current_ids = ""

        objects = lookup.get_objects(value)

        # text repr of currently selected items
        initial = []
        for obj in objects:
            display = lookup.format_item_display(obj)
            initial.append([display, obj.pk])

        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = u""

        context = {
            "name": name,
            "html_id": self.html_id,
            "current": value,
            "current_ids": current_ids,
            "current_reprs": mark_safe(simplejson.dumps(initial)),
            "help_text": help_text,
            "extra_attrs": mark_safe(flatatt(final_attrs)),
            "func_slug": self.html_id.replace("-", ""),
            "add_link": self.add_link,
        }
        context.update(plugin_options(lookup, self.channel, self.plugin_options, initial))
        context.update(bootstrap())

        return mark_safe(
            render_to_string(
                ("autocompleteselectmultiple_%s.html" % self.channel, "autocompleteselectmultiple.html"), context
            )
        )
Example #48
0
    def render(self, name, value, attrs=None):

        if value is None:
            value = []

        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)

        current_name = "" # the text field starts empty
        # eg. value = [3002L, 1194L]
        if value:
            current_ids = "|" + "|".join(str(pk) for pk in value) + "|" # |pk|pk| of current
        else:
            current_ids = "|"

        objects = lookup.get_objects(value)

        # text repr of currently selected items
        current_repr_json = []
        for obj in objects:
            repr = lookup.format_item(obj)
            current_repr_json.append("""new Array("%s",%s)""" % (
                escapejs(repr),obj.pk))

        current_reprs = mark_safe("new Array(%s)" % ",".join(current_repr_json))
        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = ''

        context = {
            'name': name,
            'html_id': self.html_id,
            'lookup_url': reverse('ajax_lookup',kwargs={'channel':self.channel}),
            'current': value,
            'current_name': current_name,
            'current_ids': current_ids,
            'current_reprs': current_reprs,
            'help_text': help_text,
            'extra_attrs': mark_safe(flatatt(final_attrs)),
            'func_slug': self.html_id.replace("-",""),
            'add_link' : self.add_link,
            'admin_media_prefix': settings.ADMIN_MEDIA_PREFIX
        }
        return mark_safe(render_to_string(('autocompleteselectmultiple_%s.html'
            % self.channel, 'autocompleteselectmultiple.html'),context))
Example #49
0
def _check_can_add(self, user, model):
    """ check if the user can add the model, deferring first to
        the channel if it implements can_add()
        else using django's default perm check.
        if it can add, then enable the widget to show the + link
    """
    lookup = get_lookup(self.channel)
    if hasattr(lookup, "can_add"):
        can_add = lookup.can_add(user, model)
    else:
        ctype = ContentType.objects.get_for_model(model)
        can_add = user.has_perm("%s.add_%s" % (ctype.app_label, ctype.model))
    if can_add:
        self.widget.add_link = reverse(
            "add_popup", kwargs={"app_label": model._meta.app_label, "model": model._meta.object_name.lower()}
        )
Example #50
0
    def render(self, name, value, attrs=None):

        value = value or ''
        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)
        current_repr = ''
        initial = None
        lookup = get_lookup(self.channel)
        if value:
            objs = lookup.get_objects([value])
            try:
                obj = objs[0]
            except IndexError:
                raise Exception("%s cannot find object:%s" % (lookup, value))
            url = lookup.get_item_url(obj)
            item_display = lookup.format_item_display(obj)
            if url:
                current_repr = '<a href="{}" target="_blank">{}</a>'.format(
                    url,
                    item_display,
                )
            else:
                current_repr = item_display
            initial = [current_repr, obj.pk]

        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = u''

        context = {
            'name': name,
            'html_id': self.html_id,
            'current_id': value,
            'current_repr': current_repr,
            'help_text': help_text,
            'extra_attrs': mark_safe(flatatt(final_attrs)),
            'func_slug': self.html_id.replace("-", ""),
            'add_link': self.add_link,
        }
        context.update(
            plugin_options(lookup, self.channel, self.plugin_options, initial))
        context.update(bootstrap())

        return mark_safe(
            render_to_string(('autocompleteselect_%s.html' % self.channel[1],
                              'autocompleteselect.html'), context))
Example #51
0
    def value_from_datadict(self, data, files, name):
        lookup = get_lookup(self.channel)
        result = []

        added_vals = getattr(lookup, 'auto_add', False) and data.getlist(
            "%s[added]" % name, [])
        if added_vals:
            for added_val in added_vals:
                added_obj = lookup.create_from_ajax_string(
                    ajax_string=added_val,
                    request_data=data,
                    form_field_name=name)
            result.append(added_obj.pk)

        for id in data.getlist(name, []):
            result.append(long(id or 0) or None)
        return result
Example #52
0
 def clean(self, value):
     """
     Subclassed clean method which returns a list of user objects.
     """
     if value:
         lookup = get_lookup(self.channel)
         objs = lookup.get_objects(value)
         if not objs:
             # Someone else might have deleted them while writing the
             # message
             if len(value) > 1:
                 error_message = _("Recipients not found")
             else:
                 error_message = _("Recipient not found")
             raise ValidationError(error_message)
         return objs
     elif self.required:
         raise ValidationError(self.error_messages['required'])
     return None
Example #53
0
def ajax_lookup(request, channel):
    """ this view supplies results for both foreign keys and many to many fields """

    # it should come in as GET unless global $.ajaxSetup({type:"POST"}) has been set
    # in which case we'll support POST
    query = request.GET['q'] if request.method == "GET" else request.POST['q']

    lookup_channel = get_lookup(channel)

    if query:
        instances = lookup_channel.get_query(query, request)
    else:
        instances = []

    results = []
    for item in instances:
        results.append(u"%s|%s|%s\n" %
                       (item.pk, lookup_channel.format_item(item),
                        lookup_channel.format_result(item)))
    return HttpResponse("\n".join(results))
Example #54
0
    def get_politicians_from_cityrep(self, politician_ids, cityrep_id):
        """ Return a list of politicians from a list of city
        representatives """

        lookup = get_lookup(CITYREP_CHANNEL_NAME)
        politicians = []

        cityrep_data = lookup.get_objects([cityrep_id
                                           ])[0]['city_representatives']

        for institution, institution_kinds in INSTITUTIONS.items():

            for inst_kind in institution_kinds:
                cityreps_of_kind = cityrep_data[institution][inst_kind]

                for politician in cityreps_of_kind:
                    if politician['politician_id'] in politician_ids:
                        politicians.append(politician['politician_id'])

        return politicians
Example #55
0
    def _clean_politician_set(self, cleaned_data, geoname_ids):
        """Return a representation of Politician objects based on 
        the data contained into an external API

        Check that the Total threshold come with the form is equal
        to the sum of politicians threshold deltas  """

        field_name = 'politician_set'
        charge_ids = [
            int(elem)
            for elem in cleaned_data[field_name].strip('|').split('|')
        ]
        charge_ids_copy = list(charge_ids)

        if charge_ids:

            politician_ids = []

            for cityrep_id in geoname_ids:
                if not len(charge_ids_copy):
                    break
                found_ids, pol_ids = self.get_politicians_from_cityrep(
                    charge_ids_copy, cityrep_id)
                for pol_id in pol_ids:
                    politician_ids.append(pol_id)
                #print("\ncityrep_id: %s\ncharge_ids_copy: %s\nfound_ids: %s\n" % (cityrep_id, charge_ids_copy, found_ids))
                for charge_id in found_ids:
                    charge_ids_copy.remove(charge_id)

            if len(charge_ids_copy):
                raise exceptions.ValidationError(
                    u"Non tutti i politici sono stati recuperati. Sono rimasti fuori i politici con id: %s"
                    % charge_ids_copy)

            lookup = get_lookup(MAP_FIELD_NAME_TO_CHANNEL[field_name])
            values = lookup.get_objects(politician_ids)

        else:
            values = []

        return values
Example #56
0
    def render(self, name, value, attrs=None):
        if value == None:
            value = ''
        html_id = attrs.get('pk', name)
        self.html_id = html_id

        lookup = get_lookup(self.channel)
        if value:
            current_name = lookup.get_objects([value])[0]
        else:
            current_name = ''
        lookup_url = reverse('ajax_lookup',kwargs={'channel':self.channel})
        vars = dict(
                name=name,
                html_id=html_id,
                lookup_url=lookup_url,
                current_id=value,
                current_name=current_name,
                help_text=self.help_text,
                extra_attrs=mark_safe(flatatt(self.attrs))
                )        
        return mark_safe(render_to_string(('autocompleteselect_%s.html' % self.channel, 'autocompleteselect.html'),vars))
Example #57
0
    def render(self, name, value, attrs=None):

        value = value or ''
        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)
        if value:
            objs = lookup.get_objects([value])
            try:
                obj = objs[0]
            except IndexError:
                raise Exception("%s cannot find object:%s" % (lookup, value))
            display = lookup.format_item_display(obj)
            current_repr = mark_safe( """new Array("%s",%s)""" % (escapejs(display),obj.pk) )
        else:
            current_repr = 'null'

        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = ''

        context = {
                'name': name,
                'html_id' : self.html_id,
                'min_length': getattr(lookup, 'min_length', 1),
                'lookup_url': reverse('ajax_lookup',kwargs={'channel':self.channel}),
                'current_id': value,
                'current_repr': current_repr,
                'help_text': help_text,
                'extra_attrs': mark_safe(flatatt(final_attrs)),
                'func_slug': self.html_id.replace("-",""),
                'add_link' : self.add_link,
                }
        context.update(bootstrap())
        
        return mark_safe(render_to_string(('autocompleteselect_%s.html' % self.channel, 'autocompleteselect.html'),context))
Example #58
0
def ajax_lookup(request, channel):
    """ this view supplies results for both foreign keys and many to many fields """
    if 'q' not in request.REQUEST:
        return HttpResponse('')  # suspicious
    query = smart_unicode(request.REQUEST['q'])
    lookup_channel = get_lookup(channel)

    if query:
        instances = lookup_channel.get_query(query, request)
    else:
        instances = []

    results = []
    for item in instances:
        itemf = lookup_channel.format_item(item)
        itemf = itemf.replace("\n", "").replace("|", "&brvbar;")
        resultf = lookup_channel.format_result(item)
        resultf = resultf.replace("\n", "").replace("|", "&brvbar;")
        results.append("|".join((unicode(item.pk), itemf, resultf)))

    if lookup_channel.auto_add and 'no_add' not in request.REQUEST:
        results.append("|".join((u'0', query, ugettext('Add as new item'))))
    return HttpResponse("\n".join(results))
Example #59
0
    def render(self, name, value, attrs=None):
        if value == None:
            value = []
        html_id = attrs.get('pk', name)
        self.html_id = html_id

        lookup = get_lookup(self.channel)
        lookup_url = reverse('ajax_lookup',kwargs={'channel':self.channel})

        current_name = ""# the text field starts empty
        # value = [3002L, 1194L]
        if value:
            current_ids = "|" + "|".join( str(pk) for pk in value ) + "|" # pk|pk of current
        else:
            current_ids = "|"

        objects = lookup.get_objects(value)

        # text repr of currently selected items
        current_repr = []
        current_repr_json = []
        for obj in objects:
            repr = lookup.format_item(obj)
            current_repr_json.append( """new Array("%s",%s)""" % (repr,obj.pk) )

        current_reprs = mark_safe("new Array(%s)" % ",".join(current_repr_json))

        vars = dict(name=name,
         html_id=html_id,
         lookup_url=lookup_url,
         current=value,
         current_name=current_name,
         current_ids=current_ids,
         current_reprs=current_reprs,
         help_text=self.help_text
         )
        return mark_safe(render_to_string(('autocompleteselectmultiple_%s.html' % self.channel, 'autocompleteselectmultiple.html'),vars))
Example #60
0
def ajax_lookup(request, channel):
    """The view used by the autocomplete widget to find products.
    """
    # it should come in as GET unless global $.ajaxSetup({type:"POST"}) has
    # been set in which case we'll support POST
    if request.method == "GET":
        query = request.GET['q']
    else:
        query = request.POST['q']
    lookup_channel = get_lookup(channel)
    if query:
        instances = lookup_channel.get_query(query, request)
    else:
        instances = []
    results = []
    for item in instances:
        itemf = lookup_channel.format_item(item)
        itemf = itemf.replace("\n", "").replace("|", "&brvbar;")
        resultf = lookup_channel.format_result(item)
        resultf = resultf.replace("\n", "").replace("|", "&brvbar;")
        results.append("|".join((unicode(item.pk), itemf, resultf)))
    return HttpResponse(
        json.dumps(results),
        mimetype='application/json')