Ejemplo n.º 1
0
def json_index(request):
	"""
	Answer to ajax requests of the client returning
	JSON serialized data.
	"""
	# give a response only if this is an ajax request
	if request.is_ajax():
		# get application label and object name
		app_label = request.GET.get('app_label')
		object_name = request.GET.get('object_name')
		
		if app_label and object_name:
			from django.db.models.loading import get_model
			# get the model
			model = get_model(app_label, object_name)
			
			if model is not None:
				from django.utils import simplejson
				# get the lookup dict
				lookup_string = request.GET.get('lookup_string', '')
				lookup_dict = utils.stringToLookup(lookup_string)
				# get the select related part
				select_related = utils._cleanValue(
					request.GET.get('select_related'))
				# get the queryset
				objects = utils.getObjects(model, lookup_dict, select_related)
				# get the raw data and dump the json
				raw_data = [(i.pk, unicode(i)) for i in objects]
				data = simplejson.dumps(raw_data)
				# return data with the right content type
				return HttpResponse(data, content_type="application/json")
				
	raise Http404
Ejemplo n.º 2
0
	def _getAllChoices(self, value):
		value = value or []
		choices = list(self.choices)
		# convert to unicode for safe comparisong during a ValidationError
		choices_keys = [unicode(i[0]) for i in choices]
		objects_to_fetch = []
		for i in value:
			if not unicode(i) in choices_keys:
				objects_to_fetch.append(i)
		if objects_to_fetch:
			objects = utils.getObjects(self.model, {"pk__in": objects_to_fetch}, self.select_related)
			for obj in objects:
				choices.append((obj.pk, unicode(obj)))
		choices.sort(key=operator.itemgetter(1))
		return choices
Ejemplo n.º 3
0
    def __init__(
        self,
        model,
        lookups,
        default_index=0,
        select_related=None,
        widget=FilteredSelectMultiple,
        filter_widget=SelectBoxFilter,
        *args,
        **kwargs
    ):
        """
		model: the related model
		lookups: a sequence of (label, lookup_dict) that tells how to
			filter the objects
			e.g. (
					('active', {'is_active': True}),
					('inactive', {'is_active': False}),
					)
			you may specify what you want in lookup_dict, give multiple
			filter lookups for the same choice and also set a choice that
			gets all unfiltered objects
			e.g. (
					('some stuff', {
						'field1__startswith': 'a',
						'field2': 'value'
						}),
					('all stuff', {}),
					)

		default_index: the index of the lookup sequence that will
			be the default choice when the field is initially displayed.
			set to None if you want the widget to start empty
			
		select_related: if not None the resulting querydict is performed
			using select_related(select_related), allowing foreign keys
			to be retrieved (e.g. useful when the unicode representation 
			of the model objects contains references to foreign keys)
			
		It is possible to pass all the other args and kwargs accepted by 
		the django field class.
		"""
        # get the default index and queryset
        # queryset is empty if default index is None
        if default_index is None:
            queryset = model.objects.none()
        else:
            lookups_list = utils.getLookups(lookups)
            if default_index >= len(lookups_list):
                default_index = 0
            lookup_dict = lookups_list[default_index][1]
            # get the queryset
            queryset = utils.getObjects(model, lookup_dict, select_related)
            # call the parent constructor
        super(AjaxManyToManyField, self).__init__(queryset, widget=widget, *args, **kwargs)
        # populate widget with some data
        self.widget.lookups = self.lookups = lookups
        self.widget.model = self.model = model
        self.widget.select_related = select_related
        self.widget.filter_widget = filter_widget()
        self.widget.default_index = default_index