예제 #1
0
def jet_select2_lookups(field):
    if hasattr(field, 'field') and \
            (isinstance(field.field, ModelChoiceField) or isinstance(field.field, ModelMultipleChoiceField)):
        qs = field.field.queryset
        model = qs.model

        if getattr(model, 'autocomplete_search_fields', None) and getattr(
                field.field, 'autocomplete', False):
            choices = []
            app_label = model._meta.app_label
            model_name = model._meta.object_name

            attrs = {
                'class':
                'ajax',
                'data-app-label':
                app_label,
                'data-model':
                model_name,
                'data-field-name':
                field.name,
                'data-ajax--url':
                reverse('jet:model_lookup') + f"?field_name={field.name}"
            }

            initial_value = field.value()

            if hasattr(field, 'field') and isinstance(
                    field.field, ModelMultipleChoiceField):
                if initial_value:
                    initial_objects = model.objects.filter(
                        pk__in=initial_value)
                    choices.extend([(initial_object.pk,
                                     get_model_instance_label(initial_object))
                                    for initial_object in initial_objects])

                if isinstance(field.field.widget, RelatedFieldWidgetWrapper):
                    field.field.widget.widget = SelectMultiple(attrs)
                else:
                    field.field.widget = SelectMultiple(attrs)
                field.field.choices = choices
            elif hasattr(field, 'field') and isinstance(
                    field.field, ModelChoiceField):
                if initial_value:
                    try:
                        initial_object = model.objects.get(pk=initial_value)
                        attrs['data-object-id'] = initial_value
                        choices.append(
                            (initial_object.pk,
                             get_model_instance_label(initial_object)))
                    except model.DoesNotExist:
                        pass

                if isinstance(field.field.widget, RelatedFieldWidgetWrapper):
                    field.field.widget.widget = Select(attrs)
                else:
                    field.field.widget = Select(attrs)
                field.field.choices = choices

    return field
예제 #2
0
def jet_select2_lookups(field):
    if hasattr(field, "field") and (isinstance(field.field, ModelChoiceField)
                                    or isinstance(field.field,
                                                  ModelMultipleChoiceField)):
        qs = field.field.queryset
        model = qs.model

        if getattr(model, "autocomplete_search_fields", None) and getattr(
                field.field, "autocomplete", True):
            choices = []
            app_label = model._meta.app_label
            model_name = model._meta.object_name

            attrs = {
                "class": "ajax",
                "data-app-label": app_label,
                "data-model": model_name,
                "data-ajax--url": reverse("jet:model_lookup"),
            }

            initial_value = field.value()

            if hasattr(field, "field") and isinstance(
                    field.field, ModelMultipleChoiceField):
                if initial_value:
                    initial_objects = model.objects.filter(
                        pk__in=initial_value)
                    choices.extend([(
                        initial_object.pk,
                        get_model_instance_label(initial_object),
                    ) for initial_object in initial_objects])

                if isinstance(field.field.widget, RelatedFieldWidgetWrapper):
                    field.field.widget.widget = SelectMultiple(attrs)
                else:
                    field.field.widget = SelectMultiple(attrs)
                field.field.choices = choices
            elif hasattr(field, "field") and isinstance(
                    field.field, ModelChoiceField):
                if initial_value:
                    try:
                        initial_object = model.objects.get(pk=initial_value)
                        attrs["data-object-id"] = initial_value
                        choices.append((
                            initial_object.pk,
                            get_model_instance_label(initial_object),
                        ))
                    except model.DoesNotExist:
                        pass

                if isinstance(field.field.widget, RelatedFieldWidgetWrapper):
                    field.field.widget.widget = Select(attrs)
                else:
                    field.field.widget = Select(attrs)
                field.field.choices = choices

    return field
예제 #3
0
def jet_select2_lookups(field):
    if hasattr(field, 'field') and isinstance(field.field, ModelChoiceField):
        qs = field.field.queryset
        model = qs.model

        if getattr(model, 'autocomplete_search_fields', None) and getattr(
                field.field, 'autocomplete', True):
            choices = []
            app_label = model._meta.app_label
            model_name = model._meta.object_name

            attrs = {
                'class': 'ajax',
                'data-app-label': app_label,
                'data-model': model_name,
                'data-ajax--url': reverse('jet:model_lookup')
            }

            form = field.form
            initial_value = form.data.get(
                field.name) if form.data != {} else form.initial.get(
                    field.name)

            if hasattr(field, 'field') and isinstance(
                    field.field, ModelMultipleChoiceField):
                if initial_value:
                    initial_objects = model.objects.filter(
                        pk__in=initial_value)
                    choices.extend([(initial_object.pk,
                                     get_model_instance_label(initial_object))
                                    for initial_object in initial_objects])

                if isinstance(field.field.widget, RelatedFieldWidgetWrapper):
                    field.field.widget.widget = SelectMultiple(attrs)
                else:
                    field.field.widget = SelectMultiple(attrs)
                field.field.choices = choices
            elif hasattr(field, 'field') and isinstance(
                    field.field, ModelChoiceField):
                if initial_value:
                    initial_object = model.objects.get(pk=initial_value)
                    attrs['data-object-id'] = initial_value
                    choices.append((initial_object.pk,
                                    get_model_instance_label(initial_object)))

                if isinstance(field.field.widget, RelatedFieldWidgetWrapper):
                    field.field.widget.widget = Select(attrs)
                else:
                    field.field.widget = Select(attrs)
                field.field.choices = choices

    return field
예제 #4
0
def jet_select2_lookups(field):
    if hasattr(field, 'field') and \
            (isinstance(field.field, ModelChoiceField) or isinstance(field.field, ModelMultipleChoiceField)):
        qs = field.field.queryset
        model = qs.model

        if getattr(model, 'autocomplete_search_fields', None) and getattr(field.field, 'autocomplete', True):
            choices = []
            app_label = model._meta.app_label
            model_name = model._meta.object_name

            attrs = {
                'class': 'ajax',
                'data-app-label': app_label,
                'data-model': model_name,
                'data-ajax--url': reverse('jet:model_lookup')
            }

            initial_value = field.value()

            if hasattr(field, 'field') and isinstance(field.field, ModelMultipleChoiceField):
                if initial_value:
                    initial_objects = model.objects.filter(pk__in=initial_value)
                    choices.extend(
                        [(initial_object.pk, get_model_instance_label(initial_object))
                            for initial_object in initial_objects]
                    )

                if isinstance(field.field.widget, RelatedFieldWidgetWrapper):
                    field.field.widget.widget = SelectMultiple(attrs)
                else:
                    field.field.widget = SelectMultiple(attrs)
                field.field.choices = choices
            elif hasattr(field, 'field') and isinstance(field.field, ModelChoiceField):
                if initial_value:
                    try:
                        initial_object = model.objects.get(pk=initial_value)
                        attrs['data-object-id'] = initial_value
                        choices.append((initial_object.pk, get_model_instance_label(initial_object)))
                    except model.DoesNotExist:
                        pass

                if isinstance(field.field.widget, RelatedFieldWidgetWrapper):
                    field.field.widget.widget = Select(attrs)
                else:
                    field.field.widget = Select(attrs)
                field.field.choices = choices

    return field
예제 #5
0
 def test_get_model_instance_label(self):
     field1 = 'value'
     field2 = 2
     pinned_application = TestModel.objects.create(field1=field1,
                                                   field2=field2)
     self.assertEqual(get_model_instance_label(pinned_application),
                      '%s%d' % (field1, field2))
예제 #6
0
    def lookup(self):
        qs = self.model_cls.objects

        if self.cleaned_data['q']:
            if getattr(self.model_cls, 'autocomplete_search_fields', None):
                search_fields = self.model_cls.autocomplete_search_fields()
                if len(search_fields) > 1:
                    filter_data = [Q((field + '__icontains', self.cleaned_data['q'])) for field in search_fields]
                else:
                    filter_data = [Q((search_fields + '__icontains', self.cleaned_data['q']))]
                # if self.cleaned_data['object_id']:
                #     filter_data.append(Q(pk=self.cleaned_data['object_id']))
                qs = qs.filter(reduce(operator.or_, filter_data))
            else:
                qs = qs.none()

        limit = self.cleaned_data['page_size'] or 100
        page = self.cleaned_data['page'] or 1
        offset = (page - 1) * limit

        items = list(map(
            lambda instance: {'id': instance.pk, 'text': get_model_instance_label(instance)},
            qs.all()[offset:offset + limit]
        ))
        total = qs.count()

        return items, total
예제 #7
0
    def lookup(self):
        qs = self.model_cls.objects

        if self.cleaned_data['q']:
            if getattr(self.model_cls, 'autocomplete_search_fields', None):
                search_fields = self.model_cls.autocomplete_search_fields()
                filter_data = [
                    Q((field + '__icontains', self.cleaned_data['q']))
                    for field in search_fields
                ]
                # if self.cleaned_data['object_id']:
                #     filter_data.append(Q(pk=self.cleaned_data['object_id']))
                qs = qs.filter(reduce(operator.or_, filter_data)).distinct()
            else:
                qs = qs.none()

        limit = self.cleaned_data['page_size'] or 100
        page = self.cleaned_data['page'] or 1
        offset = (page - 1) * limit

        items = list(
            map(
                lambda instance: {
                    'id': instance.pk,
                    'text': get_model_instance_label(instance)
                },
                qs.all()[offset:offset + limit]))
        total = qs.count()

        return items, total
예제 #8
0
파일: forms.py 프로젝트: tityrus/django-jet
    def lookup(self, user=None):
        import operator
        from jet.utils import get_model_instance_label
        from django.db.models import Q

        if 'q' in self.cleaned_data:

            if hasattr(self.model_cls,
                       'autocomplete_search_fields') and hasattr(
                           self.model_cls, 'autocomplete_search_query'):
                raise NotImplementedError(
                    "The model {} cannot have both an "
                    "autocomplete_search_fields and "
                    "autocomplete_search_query function.".format(
                        str(self.model_cls)))

            elif hasattr(self.model_cls, 'autocomplete_search_query'):
                qs = self.model_cls.autocomplete_search_query(
                    self.cleaned_data['q'], user)

            elif hasattr(self.model_cls, 'autocomplete_search_fields'):
                qs = self.model_cls.objects
                search_fields = self.model_cls.autocomplete_search_fields()
                filter_data = [
                    Q((field + '__icontains', self.cleaned_data['q']))
                    for field in search_fields
                ]
                qs = qs.filter(reduce(operator.or_, filter_data))

            else:
                qs = self.model_cls.objects.none()

        else:
            qs = self.model_cls.objects.none()

        qs = qs.distinct()

        limit = self.cleaned_data['page_size'] or 100
        page = self.cleaned_data['page'] or 1
        offset = (page - 1) * limit

        # Get count
        total = qs.count()

        # Convert qs to list of items
        items = list(qs[offset:offset + limit])

        # Optional post-processing
        if hasattr(self.model_cls, 'autocomplete_search_filter'):
            items = self.model_cls.autocomplete_search_filter(items)

        # Return dict of id and text
        items = list(
            map(
                lambda instance: {
                    'id': instance.pk,
                    'text': get_model_instance_label(instance)
                }, items))

        return items, total
예제 #9
0
    def lookup(self):
        qs = self.model_cls.objects

        if getattr(self.model_cls, "jet_lookup_queryset"):
            ctx_info = resolve(
                urlparse(
                    self.request.META.get("HTTP_REFERER", None)
                    or self.request.path_info).path)
            ctx_info.field_name = self.request.GET.get("field_name")
            qs = self.model_cls.jet_lookup_queryset(
                self.request, ctx_info)  # custom queryset from model class
        if self.cleaned_data["q"]:
            if getattr(self.model_cls, "autocomplete_search_fields", None):
                search_fields = self.model_cls.autocomplete_search_fields()
                reduce_opertaor = operator.or_
                if getattr(self.model_cls, 'generate_autocomplete_filter',
                           None):
                    filter_data, reduce_opertaor = self.model_cls.generate_autocomplete_filter(
                        self.cleaned_data['q'])
                else:
                    filter_data = [
                        Q((field + '__icontains', self.cleaned_data['q']))
                        for field in search_fields
                    ]
                # if self.cleaned_data['object_id']:
                #     filter_data.append(Q(pk=self.cleaned_data['object_id']))
                try:
                    if getattr(self.model_cls, 'autocomplete_order_fields',
                               None):
                        qs = qs.filter(reduce(
                            reduce_opertaor, filter_data)).order_by(
                                self.model_cls.autocomplete_order_fields(
                                )).distinct()
                    else:
                        qs = qs.filter(
                            reduce(reduce_opertaor,
                                   filter_data)).order_by('-pk').distinct()
                except:
                    qs = qs.filter(reduce(reduce_opertaor,
                                          filter_data)).distinct()

            else:
                qs = qs.none()

        limit = self.cleaned_data['page_size'] or 100
        page = self.cleaned_data['page'] or 1
        offset = (page - 1) * limit

        items = list(
            map(
                lambda instance: {
                    'id': instance.pk,
                    'text': get_model_instance_label(instance)
                },
                qs.all()[offset:offset + limit]))
        total = qs.count()

        return items, total
예제 #10
0
def select2_lookups(field):
    if hasattr(field, 'field') and isinstance(field.field, ModelChoiceField):
        qs = field.field.queryset
        model = qs.model

        if getattr(model, 'autocomplete_search_fields', None):
            choices = []
            app_label = model._meta.app_label
            model_name = model._meta.object_name

            attrs = {
                'class': 'ajax',
                'data-app-label': app_label,
                'data-model': model_name,
                'data-ajax--url': reverse('jet:model_lookup')
            }

            initial_value = field.form.initial.get(field.name)

            if hasattr(field, 'field') and isinstance(field.field, ModelMultipleChoiceField):
                if initial_value:
                    initial_objects = model.objects.filter(pk__in=initial_value)
                    choices.extend(
                        [(initial_object.pk, get_model_instance_label(initial_object))
                            for initial_object in initial_objects]
                    )

                field.field.widget.widget = SelectMultiple(attrs, choices=choices)
            elif hasattr(field, 'field') and isinstance(field.field, ModelChoiceField):
                if initial_value:
                    initial_object = model.objects.get(pk=initial_value)
                    attrs['data-object-id'] = initial_value
                    choices.append((initial_object.pk, get_model_instance_label(initial_object)))

                field.field.widget.widget = Select(attrs, choices=choices)

    return field
예제 #11
0
파일: forms.py 프로젝트: preusx/django-jet
    def lookup(self):
        qs = self.model_cls.objects.all()

        if getattr(self.model_cls, 'autocomplete_select_related_fields', None):
            qs = qs.select_related(
                *self.model_cls.autocomplete_select_related_fields())

        if getattr(self.model_cls, 'autocomplete_prefetch_related_fields',
                   None):
            qs = qs.prefetch_related(
                *self.model_cls.autocomplete_prefetch_related_fields())

        if getattr(self.model_cls, 'autocomplete_queryset_filters', None):
            filters = self.model_cls.autocomplete_queryset_filters()
            qs = qs.filter(**filters)

        if self.cleaned_data['q']:
            if getattr(self.model_cls, 'autocomplete_search_fields', None):
                search_fields = self.model_cls.autocomplete_search_fields()
                filter_data = [
                    Q(**{f"{field}__icontains": self.cleaned_data['q']})
                    for field in search_fields
                ]
                filter_query = reduce(operator.or_, filter_data)
                qs = qs.filter(filter_query).distinct()
            else:
                qs = qs.none()

        limit = self.cleaned_data['page_size'] or 100
        page = self.cleaned_data['page'] or 1
        offset = (page - 1) * limit

        items = [{
            'id': instance.pk,
            'text': get_model_instance_label(instance)
        } for instance in qs.distinct()[offset:offset + limit]]

        total = qs.count()

        # gives a possibility to select an empty value
        items.insert(0, {'id': 0, 'text': '----------'})

        return items, total
예제 #12
0
 def test_get_model_instance_label(self):
     field1 = 'value'
     field2 = 2
     pinned_application = TestModel.objects.create(field1=field1, field2=field2)
     self.assertEqual(get_model_instance_label(pinned_application), '%s%d' % (field1, field2))
예제 #13
0
def jet_select2_lookups(field):
    if hasattr(field, 'field') and \
            (isinstance(field.field, ModelChoiceField) or isinstance(field.field, ModelMultipleChoiceField)):
        qs = field.field.queryset
        model = qs.model

        # Define a class to be used to create select2 instance
        if getattr(field.field, 'autocomplete', True):
            css_class = 'django-jet-select'
            if 'class' in field.field.widget.widget.attrs:
                css_class = '{} {}'.format(
                    css_class, field.field.widget.widget.attrs['class'])
            field.field.widget.widget.attrs['class'] = css_class

        if getattr(model, 'autocomplete_search_fields', None) and getattr(
                field.field, 'autocomplete', True):
            choices = []
            app_label = model._meta.app_label
            model_name = model._meta.object_name

            attrs = {
                'class': 'django-jet-select ajax',
                'data-app-label': app_label,
                'data-model': model_name,
                'data-ajax--url': reverse('jet:model_lookup')
            }

            initial_value = field.value()

            if hasattr(field, 'field') and isinstance(
                    field.field, ModelMultipleChoiceField):
                if initial_value:
                    initial_objects = model.objects.filter(
                        pk__in=initial_value)
                    choices.extend([(initial_object.pk,
                                     get_model_instance_label(initial_object))
                                    for initial_object in initial_objects])

                if isinstance(field.field.widget, RelatedFieldWidgetWrapper):
                    field.field.widget.widget = SelectMultiple(attrs)
                else:
                    field.field.widget = SelectMultiple(attrs)
                field.field.choices = choices
            elif hasattr(field, 'field') and isinstance(
                    field.field, ModelChoiceField):
                if initial_value:
                    try:
                        initial_object = model.objects.get(pk=initial_value)
                        attrs['data-object-id'] = initial_value
                        choices.append(
                            (initial_object.pk,
                             get_model_instance_label(initial_object)))
                    except model.DoesNotExist:
                        pass

                if isinstance(field.field.widget, RelatedFieldWidgetWrapper):
                    field.field.widget.widget = Select(attrs)
                else:
                    field.field.widget = Select(attrs)
                field.field.choices = choices

    return field
예제 #14
0
def jet_select2_lookups(field: BoundField):
    form_field: Field = getattr(field, 'field', None)
    if not (form_field and
            (isinstance(form_field, ModelChoiceField)
             or isinstance(form_field, ModelMultipleChoiceField))):
        return field

    qs = form_field.queryset
    model = qs.model

    if not (getattr(model, 'autocomplete_search_fields', None)
            and getattr(form_field, 'autocomplete', True)):
        return field

    choices = []
    app_label = model._meta.app_label
    model_name = model._meta.object_name
    url = getattr(form_field, 'url', reverse('jet:model_lookup'))

    data = getattr(form_field.widget, 'data', {})
    data['blank'] = not form_field.required

    attrs = {
        'class': 'ajax',
        'data-app-label': app_label,
        'data-model': model_name,
        'data-ajax--url': url,
        **format_widget_data(data),
    }

    initial_value = field.value()

    if isinstance(form_field, ModelMultipleChoiceField):
        if initial_value:
            initial_objects = model.objects.filter(pk__in=initial_value)
            choices.extend([(initial_object.pk,
                             get_model_instance_label(initial_object))
                            for initial_object in initial_objects])

        if isinstance(form_field.widget, RelatedFieldWidgetWrapper):
            form_field.widget.widget = SelectMultiple(attrs)
        else:
            form_field.widget = SelectMultiple(attrs)
        form_field.choices = choices
    elif isinstance(form_field, ModelChoiceField):
        if initial_value:
            try:
                initial_object = model.objects.get(pk=initial_value)
                attrs['data-object-id'] = initial_value
                choices.append((initial_object.pk,
                                get_model_instance_label(initial_object)))
            except model.DoesNotExist:
                pass

        if isinstance(form_field.widget, RelatedFieldWidgetWrapper):
            form_field.widget.widget = Select(attrs)
        else:
            form_field.widget = Select(attrs)
        form_field.choices = choices

    return field