Esempio n. 1
0
 def test_url_params_from_lookup_dict_any_iterable(self):
     lookup1 = widgets.url_params_from_lookup_dict(
         {'color__in': ('red', 'blue')})
     lookup2 = widgets.url_params_from_lookup_dict(
         {'color__in': ['red', 'blue']})
     self.assertEqual(lookup1, {'color__in': 'red,blue'})
     self.assertEqual(lookup1, lookup2)
Esempio n. 2
0
File: tests.py Progetto: shobull/hue
    def test_url_params_from_lookup_dict_callable(self):
        def my_callable():
            return "works"

        lookup1 = widgets.url_params_from_lookup_dict({"myfield": my_callable})
        lookup2 = widgets.url_params_from_lookup_dict({"myfield": my_callable()})
        self.assertEqual(lookup1, lookup2)
Esempio n. 3
0
    def test_url_params_from_lookup_dict_callable(self):
        def my_callable():
            return 'works'

        lookup1 = widgets.url_params_from_lookup_dict({'myfield': my_callable})
        lookup2 = widgets.url_params_from_lookup_dict(
            {'myfield': my_callable()})
        self.assertEqual(lookup1, lookup2)
Esempio n. 4
0
 def genericadmin_js_init(self, request):
     if request.method == 'GET':
         obj_dict = {}
         for c in ContentType.objects.all():
             val = force_text('%s/%s' % (c.app_label, c.model))
             params = self.content_type_lookups.get('%s.%s' % (c.app_label, c.model), {})
             params = url_params_from_lookup_dict(params)
             try:
                 # Reverse the admin changelist url
                 url = reverse('admin:%s_%s_changelist' % (
                     c.app_label, c.model))
             except (NoReverseMatch, ):
                 continue
             if self.content_type_whitelist:
                 if val in self.content_type_whitelist:
                     obj_dict[c.id] = (val, params)
             elif val not in self.content_type_blacklist:
                 obj_dict[c.id] = (val, url, params)
     
         data = {
             'url_array': obj_dict,
             'fields': self.get_generic_field_list(request),
             'popup_var': IS_POPUP_VAR,
         }
         resp = json.dumps(data, ensure_ascii=False)
         return HttpResponse(resp, content_type='application/json')
     return HttpResponseNotAllowed(['GET'])
Esempio n. 5
0
    def genericadmin_js_init(self, request):
        if request.method == 'GET':
            obj_dict = {}
            for c in ContentType.objects.all():
                val = force_text('%s/%s' % (c.app_label, c.model))
                params = self.content_type_lookups.get('%s.%s' % (c.app_label, c.model), {})
                params = url_params_from_lookup_dict(params)
                if ((self.content_type_whitelist and
                        val in self.content_type_whitelist) or
                        val not in self.content_type_blacklist):
                    try:
                        model_name = unicode(c.model_class()._meta.verbose_name)
                    except AttributeError:
                        model_name = None
                    try:
                        app_label = self.app_label_override[c.app_label]
                    except (AttributeError, KeyError):
                        app_label = c.app_label

                    obj_dict[c.id] = (val, params, {'app_label': app_label,
                                                    'model_label': model_name})

            data = {
                'url_array': obj_dict,
                'fields': self.get_generic_field_list(request),
                'popup_var': IS_POPUP_VAR,
            }
            resp = json.dumps(data, ensure_ascii=False)
            return HttpResponse(resp, content_type='application/json')
        return HttpResponseNotAllowed(['GET'])
Esempio n. 6
0
    def genericadmin_js_init(self, request):
        if request.method == 'GET':
            obj_dict = {}
            for c in ContentType.objects.all():
                val = force_text('%s/%s' % (c.app_label, c.model))
                params = self.content_type_lookups.get(
                    '%s.%s' % (c.app_label, c.model), {})
                params = url_params_from_lookup_dict(params)
                if self.content_type_whitelist:
                    if val in self.content_type_whitelist:
                        obj_dict[c.id] = (reverse('admin:%s_%s_changelist' %
                                                  (c.app_label, c.model)),
                                          params)
                elif val not in self.content_type_blacklist:
                    try:
                        obj_dict[c.id] = (reverse('admin:%s_%s_changelist' %
                                                  (c.app_label, c.model)),
                                          params)
                    except NoReverseMatch:
                        pass

            data = {
                'url_array': obj_dict,
                'fields': self.get_generic_field_list(request),
                'popup_var': IS_POPUP_VAR,
            }
            resp = json.dumps(data, ensure_ascii=False)
            return HttpResponse(resp, content_type='application/json')
        return HttpResponseNotAllowed(['GET'])
Esempio n. 7
0
    def lookup_allowed(self, lookup, value):
        model = self.model
        # Check FKey lookups that are allowed, so that popups produced by
        # ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to,
        # are allowed to work.
        for l in model._meta.related_fkey_lookups:
            for k, v in widgets.url_params_from_lookup_dict(l).items():
                if k == lookup and v == value:
                    return True

        parts = lookup.split(LOOKUP_SEP)

        # Last term in lookup is a query term (__exact, __startswith etc)
        # This term can be ignored.
        if len(parts) > 1 and parts[-1] in QUERY_TERMS:
            parts.pop()

        # Special case -- foo__id__exact and foo__id queries are implied
        # if foo has been specifically included in the lookup list; so
        # drop __id if it is the last part. However, first we need to find
        # the pk attribute name.
        rel_name = None
        for part in parts[:-1]:
            try:
                field, _, _, _ = model._meta.get_field_by_name(part)
            except FieldDoesNotExist:
                # Lookups on non-existent fields are ok, since they're ignored
                # later.
                return True
            if hasattr(field, 'rel'):
                if field.rel is None:
                    # This property or relation doesn't exist, but it's allowed
                    # since it's ignored in ChangeList.get_filters().
                    return True
                model = field.rel.to
                rel_name = field.rel.get_related_field().name
            elif isinstance(field, ForeignObjectRel):
                model = field.model
                rel_name = model._meta.pk.name
            else:
                rel_name = None
        if rel_name and len(parts) > 1 and parts[-1] == rel_name:
            parts.pop()

        if len(parts) == 1:
            return True
        clean_lookup = LOOKUP_SEP.join(parts)
        return (
            clean_lookup in self.list_filter
            or clean_lookup == self.date_hierarchy)
Esempio n. 8
0
    def lookup_allowed(self, lookup, value):
        model = self.model
        # Check FKey lookups that are allowed, so that popups produced by
        # ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to,
        # are allowed to work.
        for l in model._meta.related_fkey_lookups:
            for k, v in widgets.url_params_from_lookup_dict(l).items():
                if k == lookup and v == value:
                    return True

        parts = lookup.split(LOOKUP_SEP)

        # Last term in lookup is a query term (__exact, __startswith etc)
        # This term can be ignored.
        if len(parts) > 1 and parts[-1] in QUERY_TERMS:
            parts.pop()

        # Special case -- foo__id__exact and foo__id queries are implied
        # if foo has been specifically included in the lookup list; so
        # drop __id if it is the last part. However, first we need to find
        # the pk attribute name.
        rel_name = None
        for part in parts[:-1]:
            try:
                field, _, _, _ = model._meta.get_field_by_name(part)
            except FieldDoesNotExist:
                # Lookups on non-existent fields are ok, since they're ignored
                # later.
                return True
            if hasattr(field, 'rel'):
                if field.rel is None:
                    # This property or relation doesn't exist, but it's allowed
                    # since it's ignored in ChangeList.get_filters().
                    return True
                model = field.rel.to
                rel_name = field.rel.get_related_field().name
            elif isinstance(field, ForeignObjectRel):
                model = field.model
                rel_name = model._meta.pk.name
            else:
                rel_name = None
        if rel_name and len(parts) > 1 and parts[-1] == rel_name:
            parts.pop()

        if len(parts) == 1:
            return True
        clean_lookup = LOOKUP_SEP.join(parts)
        return (clean_lookup in self.list_filter
                or clean_lookup == self.date_hierarchy)
Esempio n. 9
0
    def get_qs(self):
        """
        Returns a mapping that will be used to generate
        the query string for the api url. Any values
        in the the `limit_choices_to` specified on the
        foreign key field and any arguments specified on
        self.extra_query_kwargs are converted to a format
        that can be used in a query string and returned as
        a dictionary.
        """
        qs = url_params_from_lookup_dict(self.rel.limit_choices_to)
        if not qs:
            qs = {}

        if self.extra_query_kwargs:
            qs.update(self.extra_query_kwargs)
        return qs
Esempio n. 10
0
def get_generic_rel_list(request, blacklist=(), whitelist=(), url_params={}):
    if request.method == 'GET':
        obj_dict = {}
        for c in ContentType.objects.all().order_by('id'):
            val = u'%s/%s' % (c.app_label, c.model)
            params = url_params.get('%s.%s' % (c.app_label, c.model), {})
            params = url_params_from_lookup_dict(params)
            if whitelist:
                if val in whitelist:
                    obj_dict[c.id] = (val, params)
            else:
                if val not in blacklist:
                    obj_dict[c.id] = (val, params)

        response = HttpResponse(content_type='application/json')
        json.dump(obj_dict, response, ensure_ascii=False)
        return response
    return HttpResponseNotAllowed(['GET'])
Esempio n. 11
0
def get_generic_rel_list(request, blacklist=(), whitelist=(), url_params={}):
    if request.method == 'GET':
        obj_dict = {}
        for c in ContentType.objects.all().order_by('id'):
            val = u'%s/%s' % (c.app_label, c.model)
            params = url_params.get('%s.%s' % (c.app_label, c.model), {})
            params = url_params_from_lookup_dict(params)
            if whitelist:
                if val in whitelist:
                    obj_dict[c.id] = (val, params)
            else:
                if val not in blacklist:
                    obj_dict[c.id] = (val, params)

        response = HttpResponse(mimetype='application/json')
        json.dump(obj_dict, response, ensure_ascii=False)
        return response
    return HttpResponseNotAllowed(['GET'])
Esempio n. 12
0
	def render(self, name, value, attrs=None):
		related_url = '../../../%s/%s/' % (self.content_type.app_label, self.content_type.model)
		params = url_params_from_lookup_dict(self.limit_choices_to)
		if params:
			url = u'?' + u'&'.join([u'%s=%s' % (k, v) for k, v in params.items()])
		else:
			url = u''
		if attrs is None:
			attrs = {}
		if "class" not in attrs:
			attrs['class'] = 'vForeignKeyRawIdAdminField'
		output = [super(ModelLookupWidget, self).render(name, value, attrs)]
		output.append('<a href="%s%s" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);">' % (related_url, url, name))
		output.append('<img src="%simg/admin/selector-search.gif" width="16" height="16" alt="%s" />' % (settings.ADMIN_MEDIA_PREFIX, _('Lookup')))
		output.append('</a>')
		if value:
			value_class = self.content_type.model_class()
			try:
				value_object = value_class.objects.get(pk=value)
				output.append('&nbsp;<strong>%s</strong>' % escape(truncate_words(value_object, 14)))
			except value_class.DoesNotExist:
				pass
		return mark_safe(u''.join(output))
Esempio n. 13
0
 def test_url_params_from_lookup_dict_any_iterable(self):
     lookup1 = url_params_from_lookup_dict({'color__in': ('red', 'blue')})
     lookup2 = url_params_from_lookup_dict({'color__in': ['red', 'blue']})
     self.assertEqual(lookup1, {'color__in': 'red,blue'})
     self.assertEqual(lookup1, lookup2)
Esempio n. 14
0
 def get_qs(self):
     return url_params_from_lookup_dict(self.limit_choices_to)
Esempio n. 15
0
 def get_qs(self):
     return url_params_from_lookup_dict(self.limit_choices_to)
Esempio n. 16
0
 def url_parameters(self):
     params = super().url_parameters()
     params.update(
         url_params_from_lookup_dict({"sub_courses__isnull": True}))
     return params
Esempio n. 17
0
File: tests.py Progetto: shobull/hue
 def test_url_params_from_lookup_dict_any_iterable(self):
     lookup1 = widgets.url_params_from_lookup_dict({"color__in": ("red", "blue")})
     lookup2 = widgets.url_params_from_lookup_dict({"color__in": ["red", "blue"]})
     self.assertEqual(lookup1, {"color__in": "red,blue"})
     self.assertEqual(lookup1, lookup2)
Esempio n. 18
0
 def base_url_parameters(self):
     from django.contrib.admin.widgets import url_params_from_lookup_dict
     return url_params_from_lookup_dict(self.limit_choices_to)
Esempio n. 19
0
 def get_limit_choices_to_params(self):
     limit_choices_to = self.remote_field.limit_choices_to
     if callable(limit_choices_to):
         limit_choices_to = limit_choices_to()
     return widgets.url_params_from_lookup_dict(limit_choices_to)