예제 #1
0
 def test_model_choices(self):
     mis = SearchSite()
     mis.register(MockModel)
     mis.register(AnotherMockModel)
     self.assertEqual(len(model_choices(site=mis)), 2)
     self.assertEqual([option[1] for option in model_choices(site=mis)],
                      [u'Another mock models', u'Mock models'])
예제 #2
0
    def __init__(self, *args, **kwargs):
        if 'searchqueryset' not in kwargs.keys(
        ) or kwargs['searchqueryset'] is None:
            kwargs['searchqueryset'] = get_permission_sqs()
        if not issubclass(type(kwargs['searchqueryset']),
                          PermissionSearchQuerySet):
            raise ImproperlyConfigured(
                "Aristotle Search Queryset connection must be a subclass of PermissionSearchQuerySet"
            )
        super().__init__(*args, **kwargs)

        # Populate choice of Registration Authorities ordered by active state and name
        # Inactive last
        self.fields['ra'].choices = [
            (ra.id, ra.name)
            for ra in MDR.RegistrationAuthority.objects.filter(
                active__in=[0, 1]).order_by('active', 'name')
        ]

        # List of models that you can search for

        self.default_models = [
            m[0] for m in model_choices()
            if m[0].split('.', 1)[0] in allowable_search_models()
        ]

        # Set choices for models
        self.fields['models'].choices = [
            m for m in model_choices()
            if m[0].split('.', 1)[0] in allowable_search_models()
        ]
예제 #3
0
 def test_model_choices_unicode(self):
     stowed_verbose_name_plural = MockModel._meta.verbose_name_plural
     MockModel._meta.verbose_name_plural = '☃'
     self.assertEqual(len(model_choices()), 2)
     self.assertEqual([option[1] for option in model_choices()],
                      ['Another mock models', '☃'])
     MockModel._meta.verbose_name_plural = stowed_verbose_name_plural
예제 #4
0
 def test_model_choices_unicode(self):
     stowed_verbose_name_plural = MockModel._meta.verbose_name_plural
     MockModel._meta.verbose_name_plural = "☃"
     self.assertEqual(len(model_choices()), 2)
     self.assertEqual(
         [option[1] for option in model_choices()], ["Another mock models", "☃"]
     )
     MockModel._meta.verbose_name_plural = stowed_verbose_name_plural
예제 #5
0
파일: forms.py 프로젝트: jsnhff/rhizome.org
 def __init__(self, *args, **kwargs):
     super(RhizomeModelSearchForm, self).__init__(*args, **kwargs)
     self.fields['models'] = forms.MultipleChoiceField(
         choices=model_choices(),
         required=False,
         label=_('Search In'),
         widget=SearchCheckboxSelectMultiple)
예제 #6
0
 def __init__(self, *args, **kwargs):
     super(ModelSearchForm, self).__init__(*args, **kwargs)
     self.fields['models'] = forms.MultipleChoiceField(
         choices=model_choices(),
         required=False,
         label=FieldSearchForm.SEARCH_IN,
         widget=forms.CheckboxSelectMultiple)
예제 #7
0
class Search(models.Model):
    choices = model_choices()

    title = models.CharField(_('title'),
                             max_length=100,
                             help_text=_('Give the name of search box.'))
    category = models.CharField(_('category'),
                                max_length=50,
                                choices=choices,
                                help_text=_('Select the model for searching.'))
    manager = models.ForeignKey(SearchManager)

    def clean(self):
        """
        Don't allow other search with the same searchmanager has the same category
        :return:
        """
        searches_category = Search.objects.filter(
            manager=self.manager, category=self.category).exclude(pk=self.pk)
        searches_title = Search.objects.filter(
            manager=self.manager, title=self.title).exclude(pk=self.pk)
        if searches_category.count() != 0:
            msg = _('In this manager is already exist this category.')
            raise ValidationError({'category': msg})

        if searches_title.count() != 0:
            msg = _('In this manager is already exist this title.')
            raise ValidationError({'title': msg})

    def __unicode__(self):
        return self.title
예제 #8
0
    def __init__(self, *args, **kwargs):
        kwargs['searchqueryset'] = PermissionSearchQuerySet()
        super(PermissionSearchForm, self).__init__(*args, **kwargs)
        from haystack.forms import SearchForm, FacetedSearchForm, model_choices

        self.fields['ra'].choices = [(ra.id, ra.name) for ra in MDR.RegistrationAuthority.objects.all()]
        self.fields['models'].choices = model_choices()
예제 #9
0
    def __init__(self, *args, **kwargs):
        """
        If we're in a recognised faceting engine, display and allow faceting.
        """
        super(PreSelectedModelSearchForm, self).__init__(*args, **kwargs)
        if 'models' in self.fields:
            self.fields['models'].initial = [x[0] for x in model_choices()]
            self.fields['models'].label = _("Only models")
        self.haystack_config = HaystackConfig()

        self.fields['content_field'].choices = content_field_choices()

        self.version = self.haystack_config.version
        if self.should_allow_faceting():
            possible_facets = self.configure_faceting()
            self.fields['possible_facets'].choices = possible_facets
            self.fields['selected_facets'] = SelectedFacetsField(
                choices=(), required=False, possible_facets=possible_facets)

        if self.has_multiple_connections():
            wtf = self.get_possible_connections()
            self.fields['connection'].choices = tuple(wtf)  # noqa
            self.fields['connection'].initial = 'default'
        else:
            self.fields['connection'].widget = HiddenInput()
예제 #10
0
    def __init__(self, *args, **kwargs):
        kwargs['searchqueryset'] = PermissionSearchQuerySet()
        super(PermissionSearchForm, self).__init__(*args, **kwargs)

        self.fields['ra'].choices = [
            (ra.id, ra.name) for ra in MDR.RegistrationAuthority.objects.all()
        ]
        self.fields['models'].choices = model_choices()
예제 #11
0
 def __init__(self, *args, **kwargs):
     super(_ModelSearchForm, self).__init__(*args, **kwargs)
     extra_choices = [v[1] for v in self.extra_model_choices.values()]
     self.fields['resource'] = forms.MultipleChoiceField(
         choices=model_choices() + extra_choices,
         required=False,
         label=_('Search In'),
         widget=forms.CheckboxSelectMultiple)
예제 #12
0
 def clean_model(self):
     if self.cleaned_data.get('model'):
         model = self.cleaned_data.get('model')
         hchoices = haystack_forms.model_choices()
         if model in [hch[0] for hch in hchoices]:
             self.cleaned_data['model'] =\
                 models.get_model(*model.split('.'))
             return self.cleaned_data['model']
         raise forms.ValidationError("invalid search model")
예제 #13
0
 def clean_model(self):
     if self.cleaned_data.get('model'):
         model = self.cleaned_data.get('model')
         hchoices = haystack_forms.model_choices()
         if model in [hch[0] for hch in hchoices]:
             self.cleaned_data['model'] =\
                 models.get_model(*model.split('.'))
             return self.cleaned_data['model']
         raise forms.ValidationError("invalid search model")
예제 #14
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     choices = hay_forms.model_choices()
     self.fields["models"] = forms.ChoiceField(choices=choices,
                                               required=False,
                                               label='Искать',
                                               widget=forms.RadioSelect,
                                               initial=choices[0][0])
     self.stopwords = set(stopwords.words('russian'))
     self.stemmer = RussianStemmer()
     self.tokenizer = RegexpTokenizer(r'\w+')
예제 #15
0
    def __init__(self, *args, **kwargs):
        super(AninstanceSearchForm, self).__init__(*args, **kwargs)

        # Only used if inheriting from ModelSearchForm (not SearchForm)
        self.fields['models'] = forms.MultipleChoiceField(
            choices=model_choices(),
            required=False,
            label=_('Search in'),
            widget=forms.CheckboxSelectMultiple(
                attrs={'class': 'form-control'}),
        )
예제 #16
0
    def __init__(self, *args, **kwargs):
        if 'searchqueryset' not in kwargs.keys() or kwargs['searchqueryset'] is None:
            kwargs['searchqueryset'] = get_permission_sqs()
        if not issubclass(type(kwargs['searchqueryset']), PermissionSearchQuerySet):
            raise ImproperlyConfigured("Aristotle Search Queryset connection must be a subclass of PermissionSearchQuerySet")
        super().__init__(*args, **kwargs)

        self.fields['ra'].choices = [(ra.id, ra.name) for ra in MDR.RegistrationAuthority.objects.all()]

        self.fields['models'].choices = [
            m for m in model_choices()
            if m[0].split('.', 1)[0] in fetch_metadata_apps() + ['aristotle_mdr_help']
        ]
예제 #17
0
    def get_ultimas_publicacoes_uma_por_tipo__nao_usada(self):
        search_models = model_choices()

        results = []

        for m in search_models:
            sqs = SearchQuerySet().all()
            sqs = sqs.filter(at=0)
            sqs = sqs.models(*haystack_get_models(m[0]))
            sqs = sqs.order_by('-data', '-last_update')[:5]
            if len(sqs):
                results.append(sqs[0])

        return results
예제 #18
0
    def __init__(self, *args, **kwargs):
        if 'searchqueryset' not in kwargs.keys() or kwargs['searchqueryset'] is None:
            kwargs['searchqueryset'] = get_permission_sqs()
        if not issubclass(type(kwargs['searchqueryset']), PermissionSearchQuerySet):
            raise ImproperlyConfigured("Aristotle Search Queryset connection must be a subclass of PermissionSearchQuerySet")
        super().__init__(*args, **kwargs)

        # Show visible workgroups ordered by active state and name
        # Inactive last
        self.fields['ra'].choices = [(ra.id, ra.name) for ra in MDR.RegistrationAuthority.objects.filter(active__in=[0, 1]).order_by('active', 'name')]

        self.fields['models'].choices = [
            m for m in model_choices()
            if m[0].split('.', 1)[0] in fetch_metadata_apps() + ['aristotle_mdr_help']
        ]
    def __init__(self, *args, **kwargs):
        if 'searchqueryset' not in kwargs.keys() or kwargs['searchqueryset'] is None:
            kwargs['searchqueryset'] = get_permission_sqs()
        if not issubclass(type(kwargs['searchqueryset']), PermissionSearchQuerySet):
            raise ImproperlyConfigured("Aristotle Search Queryset connection must be a subclass of PermissionSearchQuerySet")
        super().__init__(*args, **kwargs)

        # Show visible workgroups ordered by active state and name
        # Inactive last
        self.fields['ra'].choices = [(ra.id, ra.name) for ra in MDR.RegistrationAuthority.objects.filter(active__in=[0, 1]).order_by('active', 'name')]

        self.fields['models'].choices = [
            m for m in model_choices()
            if m[0].split('.', 1)[0] in fetch_metadata_apps() + ['aristotle_mdr_help']
        ]
예제 #20
0
    def __init__(self, *args, **kwargs):
        if 'searchqueryset' not in kwargs.keys(
        ) or kwargs['searchqueryset'] is None:
            kwargs['searchqueryset'] = PermissionSearchQuerySet()
        if not issubclass(type(kwargs['searchqueryset']),
                          PermissionSearchQuerySet):
            raise ImproperlyConfigured(
                "Aristotle Search Queryset connection must be a subclass of PermissionSearchQuerySet"
            )
        super(PermissionSearchForm, self).__init__(*args, **kwargs)

        from haystack.forms import SearchForm, FacetedSearchForm, model_choices

        self.fields['ra'].choices = [
            (ra.id, ra.name) for ra in MDR.RegistrationAuthority.objects.all()
        ]
        self.fields['models'].choices = model_choices()
예제 #21
0
    def __init__(self, *args, **kwargs):
        """
        If we're in a recognised faceting engine, display and allow faceting.
        """
        super(PreSelectedModelSearchForm, self).__init__(*args, **kwargs)
        if "models" in self.fields:
            self.fields["models"].initial = [x[0] for x in model_choices()]
            self.fields["models"].label = _("Only models")

        # provide support for discovering the version installed.
        self.version = self.guess_haystack_version()
        if self.should_allow_faceting():
            possible_facets = self.configure_faceting()
            self.fields["possible_facets"].choices = possible_facets
            self.fields["selected_facets"] = SelectedFacetsField(
                choices=(), required=False, possible_facets=possible_facets
            )

        if self.has_multiple_connections():
            wtf = self.get_possible_connections()
            self.fields["connection"].choices = tuple(wtf)  # noqa
            self.fields["connection"].initial = "default"
        else:
            self.fields["connection"].widget = HiddenInput()
예제 #22
0
class PermissionSearchForm(TokenSearchForm):
    """
        We need to make a new form as permissions to view objects are a bit finicky.
        This form allows us to perform the base query then restrict it to just those
        of interest.

        TODO: This might not scale well, so it may need to be looked at in production.
    """
    mq = forms.ChoiceField(required=False,
                           initial=QUICK_DATES.anytime,
                           choices=QUICK_DATES,
                           widget=BootstrapDropdownIntelligentDate)
    mds = forms.DateField(required=False,
                          label="Modified after date",
                          widget=DateTimePicker(options=datePickerOptions))
    mde = forms.DateField(required=False,
                          label="Modified before date",
                          widget=DateTimePicker(options=datePickerOptions))
    cq = forms.ChoiceField(required=False,
                           initial=QUICK_DATES.anytime,
                           choices=QUICK_DATES,
                           widget=BootstrapDropdownIntelligentDate)
    cds = forms.DateField(required=False,
                          label="Created after date",
                          widget=DateTimePicker(options=datePickerOptions))
    cde = forms.DateField(required=False,
                          label="Created before date",
                          widget=DateTimePicker(options=datePickerOptions))

    # Use short singular names
    # ras = [(ra.id, ra.name) for ra in MDR.RegistrationAuthority.objects.all()]
    ra = forms.MultipleChoiceField(required=False,
                                   label=_("Registration authority"),
                                   choices=[],
                                   widget=BootstrapDropdownSelectMultiple)

    sort = forms.ChoiceField(required=False,
                             initial=SORT_OPTIONS.natural,
                             choices=SORT_OPTIONS,
                             widget=BootstrapDropdownSelect)
    from aristotle_mdr.search_indexes import BASE_RESTRICTION
    res = forms.ChoiceField(required=False,
                            initial=None,
                            choices=BASE_RESTRICTION.items(),
                            label="Item visibility state")

    state = forms.MultipleChoiceField(required=False,
                                      label=_("Registration status"),
                                      choices=MDR.STATES,
                                      widget=BootstrapDropdownSelectMultiple)
    public_only = forms.BooleanField(required=False,
                                     label="Only show public items")
    myWorkgroups_only = forms.BooleanField(
        required=False, label="Only show items in my workgroups")
    models = forms.MultipleChoiceField(choices=model_choices(),
                                       required=False,
                                       label=_('Item type'),
                                       widget=BootstrapDropdownSelectMultiple)

    def __init__(self, *args, **kwargs):
        kwargs['searchqueryset'] = PermissionSearchQuerySet()
        super(PermissionSearchForm, self).__init__(*args, **kwargs)

        self.fields['ra'].choices = [
            (ra.id, ra.name) for ra in MDR.RegistrationAuthority.objects.all()
        ]
        self.fields['models'].choices = model_choices()

    def get_models(self):
        """Return an alphabetical list of model classes in the index."""
        search_models = []

        if self.is_valid() and self.cleaned_data['models']:
            for model in self.cleaned_data['models']:
                search_models.append(models.get_model(*model.split('.')))

        return search_models

    filters = "models mq cq cds cde mds mde state ra res".split()

    @property
    def applied_filters(self):
        if not hasattr(self, 'cleaned_data'):
            return []
        return [f for f in self.filters if self.cleaned_data.get(f, False)]

    def search(self, repeat_search=False):
        # First, store the SearchQuerySet received from other processing.
        sqs = super(PermissionSearchForm, self).search()
        if not self.token_models:
            sqs = sqs.models(*self.get_models())
        self.repeat_search = repeat_search

        has_filter = self.kwargs or self.token_models or self.applied_filters
        if not has_filter and not self.query_text:
            return self.no_query_found()

        if self.applied_filters and not self.query_text:  # and not self.kwargs:
            # If there is a filter, but no query then we'll force some results.
            sqs = self.searchqueryset.order_by('-modified')
            self.filter_search = True
            self.attempted_filter_search = True

        states = self.cleaned_data['state']
        ras = self.cleaned_data['ra']
        restriction = self.cleaned_data['res']
        sqs = sqs.apply_registration_status_filters(states, ras)

        if restriction:
            sqs = sqs.filter(restriction=restriction)

        sqs = self.apply_date_filtering(sqs)
        sqs = sqs.apply_permission_checks(
            user=self.request.user,
            public_only=self.cleaned_data['public_only'],
            user_workgroups_only=self.cleaned_data['myWorkgroups_only'])

        self.has_spelling_suggestions = False
        if not self.repeat_search:

            if sqs.count() < 5:
                self.check_spelling(sqs)

            if sqs.count() == 0:
                if sqs.count() == 0 and self.has_spelling_suggestions:
                    self.auto_correct_spell_search = True
                    self.cleaned_data['q'] = self.suggested_query
                elif has_filter and self.cleaned_data['q']:
                    # If there are 0 results with a search term, and filters applied
                    # lets be nice and remove the filters and try again.
                    # There will be a big message on the search page that says what we did.
                    for f in self.filters:
                        self.cleaned_data[f] = None
                    self.auto_broaden_search = True
                # Re run the query with the updated details
                sqs = self.search(repeat_search=True)
            # Only apply sorting on the first pass through
            sqs = self.apply_sorting(sqs)

        filters_to_facets = {
            'ra': 'registrationAuthorities',
            'models': 'facet_model_ct',
            'state': 'statuses',
        }
        for _filter, facet in filters_to_facets.items():
            if _filter not in self.applied_filters:
                sqs = sqs.facet(facet, sort='count')

        logged_in_facets = {'wg': 'workgroup', 'res': 'restriction'}
        if self.request.user.is_active:
            for _filter, facet in logged_in_facets.items():
                if _filter not in self.applied_filters:
                    sqs = sqs.facet(facet, sort='count')

        self.facets = sqs.facet_counts()
        if 'fields' in self.facets:
            for facet, counts in self.facets['fields'].items():
                # Return the 5 top results for each facet in order of number of results.
                self.facets['fields'][facet] = sorted(counts,
                                                      key=lambda x: -x[1])[:5]

        return sqs

    def check_spelling(self, sqs):
        if self.query_text:
            original_query = self.cleaned_data.get('q', "")

            from urllib import quote_plus
            suggestions = []
            has_suggestions = False
            suggested_query = []

            # lets assume the words are ordered in importance
            # So we suggest words in order
            optimal_query = original_query
            for token in self.cleaned_data.get('q', "").split(" "):
                if token:  # remove blanks
                    suggestion = self.searchqueryset.spelling_suggestion(token)
                    if suggestion:
                        test_query = optimal_query.replace(token, suggestion)
                        # Haystack can *over correct* so we'll do a quick search with the
                        # suggested spelling to compare words against
                        try:
                            PermissionSearchQuerySet().auto_query(
                                test_query)[0]
                            suggested_query.append(suggestion)
                            has_suggestions = True
                            optimal_query = test_query
                        except:
                            suggestion = None
                    else:
                        suggested_query.append(token)
                    suggestions.append((token, suggestion))
            if optimal_query != original_query:
                self.spelling_suggestions = suggestions
                self.has_spelling_suggestions = has_suggestions
                self.original_query = self.cleaned_data.get('q')
                self.suggested_query = quote_plus(' '.join(suggested_query),
                                                  safe="")

    def apply_date_filtering(self, sqs):
        modify_quick_date = self.cleaned_data['mq']
        create_quick_date = self.cleaned_data['cq']
        create_date_start = self.cleaned_data['cds']
        create_date_end = self.cleaned_data['cde']
        modify_date_start = self.cleaned_data['mds']
        modify_date_end = self.cleaned_data['mde']
        """
        Modified filtering is really hard to do formal testing for as the modified
        dates are altered on save, so its impossible to alter the modified dates
        to check the search is working.
        However, this is the exact same process as creation date (which we can alter),
        so if creation filtering is working, modified filtering should work too.
        """
        if modify_quick_date and modify_quick_date is not QUICK_DATES.anytime:  # pragma: no cover
            delta = time_delta(modify_quick_date)
            if delta is not None:
                sqs = sqs.filter(modifed__gte=delta)
        elif modify_date_start or modify_date_end:  # pragma: no cover
            if modify_date_start:
                sqs = sqs.filter(modifed__gte=modify_date_start)
            if modify_date_end:
                sqs = sqs.filter(modifed__lte=modify_date_end)

        if create_quick_date and create_quick_date is not QUICK_DATES.anytime:
            delta = time_delta(create_quick_date)
            if delta is not None:
                sqs = sqs.filter(created__gte=delta)
        elif create_date_start or create_date_end:
            if create_date_start:
                sqs = sqs.filter(created__gte=create_date_start)
            if create_date_end:
                sqs = sqs.filter(created__lte=create_date_end)

        return sqs

    def apply_sorting(
        self, sqs
    ):  # pragma: no cover, no security issues, standard Haystack methods, so already tested.
        sort_order = self.cleaned_data['sort']
        if sort_order == SORT_OPTIONS.modified_ascending:
            sqs = sqs.order_by('-modified')
        elif sort_order == SORT_OPTIONS.modified_descending:
            sqs = sqs.order_by('modified')
        elif sort_order == SORT_OPTIONS.created_ascending:
            sqs = sqs.order_by('-created')
        elif sort_order == SORT_OPTIONS.created_descending:
            sqs = sqs.order_by('created')
        elif sort_order == SORT_OPTIONS.alphabetical:
            sqs = sqs.order_by('name')
        elif sort_order == SORT_OPTIONS.state:
            sqs = sqs.order_by('-highest_state')

        return sqs
예제 #23
0
 def test_model_choices(self):
     self.assertEqual(len(model_choices()), 2)
     self.assertEqual([option[1] for option in model_choices()], [u'Another mock models', u'Mock models'])
    def index(self, request):
        """The view for showing all the results in the Haystack index. Emulates
        the standard Django ChangeList mostly.

        :param request: the current request.
        :type request: WSGIRequest

        :return: A template rendered into an HttpReponse
        """
        page_var = self.get_paginator_var(request)
        form = PreSelectedModelSearchForm(request.GET or None, load_all=False)

        # Make sure there are some models indexed
        available_models = model_choices()
        if len(available_models) < 0:
            raise Http404

        # We've not selected any models, so we're going to redirect and select
        # all of them. This will bite me in the ass if someone searches for a string
        # but no models, but I don't know WTF they'd expect to return, anyway.
        # Note that I'm only doing this to sidestep this issue:
        # https://gist.github.com/3766607
        if 'models' not in request.GET.keys():
            # TODO: make this betterererer.
            new_qs = ['&models=%s' % x[0] for x in available_models]
            # if we're in haystack2, we probably want to provide the 'default'
            # connection so that it behaves as if "initial" were in place.
            if form.has_multiple_connections():
                new_qs.append('&connection=' + form.fields['connection'].initial)
            new_qs = ''.join(new_qs)
            qs = self.get_current_query_string(request, remove=['p'])
            return HttpResponseRedirect(request.path_info + qs + new_qs)

        try:
            sqs = form.search()
            try:
                page_no = int(request.GET.get(PAGE_VAR, 0))
            except ValueError:
                page_no = 0
            #page_no = int(request.GET.get(page_var, 1))
            results_per_page = self.get_results_per_page(request)
            paginator = Paginator(sqs, results_per_page)
            page = paginator.page(page_no+1)
        except (InvalidPage, ValueError):
            # paginator.page may raise InvalidPage if we've gone too far
            # meanwhile, casting the querystring parameter may raise ValueError
            # if it's None, or '', or other silly input.
            raise Http404

        query = request.GET.get(self.get_search_var(request), None)
        connection = request.GET.get('connection', None)
        title = self.model._meta.verbose_name_plural
        if query:
            title = string_concat(self.model._meta.verbose_name_plural, ' for "',
                                  query, '"')
        if connection:
            title = string_concat(title, ' using "', connection, '" connection')
        context = {
            'results': self.get_wrapped_search_results(page.object_list),
            'pagination_required': page.has_other_pages(),
            'page_range': paginator.page_range,
            'page_num': page.number,
            'result_count': paginator.count,
            'opts': self.model._meta,
            'title': force_unicode(title),
            'root_path': getattr(self.admin_site, 'root_path', None),
            'app_label': self.model._meta.app_label,
            'filtered': True,
            'form': form,
            'query_string': self.get_current_query_string(request, remove=['p']),
            'search_model_count': len(request.GET.getlist('models')),
            'search_facet_count': len(request.GET.getlist('possible_facets')),
            'search_var': self.get_search_var(request),
            'page_var': page_var,
            'facets': FacetWrapper(sqs.facet_counts()),
            'module_name': force_unicode(self.model._meta.verbose_name_plural),
            'cl': FakeChangeListForPaginator(request, page, results_per_page, self.model._meta),
            'haystack_version': _haystack_version,
            # Note: the empty Media object isn't specficially required for the
            # standard Django admin, but is apparently a pre-requisite for
            # things like Grappelli.
            # See #1 (https://github.com/kezabelle/django-haystackbrowser/pull/1)
            'media': Media()
        }
        return render_to_response('admin/haystackbrowser/result_list.html', context,
                                  context_instance=RequestContext(request))
예제 #25
0
 def test_model_choices(self):
     mis = SearchSite()
     mis.register(MockModel)
     mis.register(AnotherMockModel)
     self.assertEqual(len(model_choices(site=mis)), 2)
     self.assertEqual([option[1] for option in model_choices(site=mis)], [u'Another mock models', u'Mock models'])
예제 #26
0
    def index(self, request):
        """The view for showing all the results in the Haystack index. Emulates
        the standard Django ChangeList mostly.

        :param request: the current request.
        :type request: WSGIRequest

        :return: A template rendered into an HttpReponse
        """
        if not self.has_change_permission(request, None):
            raise PermissionDenied("Not a superuser")

        page_var = self.get_paginator_var(request)
        form = PreSelectedModelSearchForm(request.GET or None, load_all=False)
        minimum_page = form.fields[page_var].min_value
        # Make sure there are some models indexed
        available_models = model_choices()
        if len(available_models) <= 0:
            raise Search404('No search indexes bound via Haystack')

        # We've not selected any models, so we're going to redirect and select
        # all of them. This will bite me in the ass if someone searches for a string
        # but no models, but I don't know WTF they'd expect to return, anyway.
        # Note that I'm only doing this to sidestep this issue:
        # https://gist.github.com/3766607
        if 'models' not in request.GET.keys():
            # TODO: make this betterererer.
            new_qs = ['&models=%s' % x[0] for x in available_models]
            # if we're in haystack2, we probably want to provide the 'default'
            # connection so that it behaves as if "initial" were in place.
            if form.has_multiple_connections():
                new_qs.append('&connection=' +
                              form.fields['connection'].initial)
            new_qs = ''.join(new_qs)
            existing_query = request.GET.copy()
            if page_var in existing_query:
                existing_query.pop(page_var)
            existing_query[page_var] = minimum_page
            location = '%(path)s?%(existing_qs)s%(new_qs)s' % {
                'existing_qs': existing_query.urlencode(),
                'new_qs': new_qs,
                'path': request.path_info,
            }
            return HttpResponseRedirect(location)

        sqs = form.search()
        cleaned_GET = form.cleaned_data_querydict
        try:
            page_no = int(cleaned_GET.get(PAGE_VAR, minimum_page))
        except ValueError:
            page_no = minimum_page
        results_per_page = self.get_results_per_page(request)
        paginator = Paginator(sqs, results_per_page)
        try:
            page = paginator.page(page_no + 1)
        except (InvalidPage, ValueError):
            # paginator.page may raise InvalidPage if we've gone too far
            # meanwhile, casting the querystring parameter may raise ValueError
            # if it's None, or '', or other silly input.
            raise Search404("Invalid page")

        query = request.GET.get(self.get_search_var(request), None)
        connection = request.GET.get('connection', None)
        title = self.model._meta.verbose_name_plural

        wrapped_facets = FacetWrapper(
            sqs.facet_counts(), querydict=form.cleaned_data_querydict.copy())

        context = {
            'results':
            self.get_wrapped_search_results(page.object_list),
            'pagination_required':
            page.has_other_pages(),
            # this may be expanded into xrange(*page_range) to copy what
            # the paginator would yield. This prevents 50000+ pages making
            # the page slow to render because of django-debug-toolbar.
            'page_range': (1, paginator.num_pages + 1),
            'page_num':
            page.number,
            'result_count':
            paginator.count,
            'opts':
            self.model._meta,
            'title':
            force_text(title),
            'root_path':
            getattr(self.admin_site, 'root_path', None),
            'app_label':
            self.model._meta.app_label,
            'filtered':
            True,
            'form':
            form,
            'form_valid':
            form.is_valid(),
            'query_string':
            self.get_current_query_string(request, remove=[page_var]),
            'search_model_count':
            len(cleaned_GET.getlist('models')),
            'search_facet_count':
            len(cleaned_GET.getlist('possible_facets')),
            'search_var':
            self.get_search_var(request),
            'page_var':
            page_var,
            'facets':
            wrapped_facets,
            'applied_facets':
            form.applied_facets(),
            'module_name':
            force_text(self.model._meta.verbose_name_plural),
            'cl':
            FakeChangeListForPaginator(request, page, results_per_page,
                                       self.model._meta),
            'haystack_version':
            _haystack_version,
            # Note: the empty Media object isn't specficially required for the
            # standard Django admin, but is apparently a pre-requisite for
            # things like Grappelli.
            # See #1 (https://github.com/kezabelle/django-haystackbrowser/pull/1)
            'media':
            Media()
        }
        # Update the context with variables that should be available to every page
        context.update(self.each_context_compat(request))
        return self.do_render(
            request=request,
            template_name='admin/haystackbrowser/result_list.html',
            context=context)
예제 #27
0
    def index(self, request):
        """The view for showing all the results in the Haystack index. Emulates
        the standard Django ChangeList mostly.

        :param request: the current request.
        :type request: WSGIRequest

        :return: A template rendered into an HttpReponse
        """
        page_var = self.get_paginator_var(request)
        form = PreSelectedModelSearchForm(request.GET or None, load_all=False)

        # Make sure there are some models indexed
        available_models = model_choices()
        if len(available_models) < 0:
            raise Http404

        # We've not selected any models, so we're going to redirect and select
        # all of them. This will bite me in the ass if someone searches for a string
        # but no models, but I don't know WTF they'd expect to return, anyway.
        # Note that I'm only doing this to sidestep this issue:
        # https://gist.github.com/3766607
        if 'models' not in request.GET.keys():
            # TODO: make this betterererer.
            new_qs = ['&models=%s' % x[0] for x in available_models]
            # if we're in haystack2, we probably want to provide the 'default'
            # connection so that it behaves as if "initial" were in place.
            if form.has_multiple_connections():
                new_qs.append('&connection=' +
                              form.fields['connection'].initial)
            new_qs = ''.join(new_qs)
            qs = self.get_current_query_string(request, remove=['p'])
            return HttpResponseRedirect(request.path_info + qs + new_qs)

        try:
            sqs = form.search()
            try:
                page_no = int(request.GET.get(PAGE_VAR, 0))
            except ValueError:
                page_no = 0
            #page_no = int(request.GET.get(page_var, 1))
            results_per_page = self.get_results_per_page(request)
            paginator = Paginator(sqs, results_per_page)
            page = paginator.page(page_no + 1)
        except (InvalidPage, ValueError):
            # paginator.page may raise InvalidPage if we've gone too far
            # meanwhile, casting the querystring parameter may raise ValueError
            # if it's None, or '', or other silly input.
            raise Http404

        query = request.GET.get(self.get_search_var(request), None)
        connection = request.GET.get('connection', None)
        title = self.model._meta.verbose_name_plural
        if query:
            title = string_concat(self.model._meta.verbose_name_plural,
                                  ' for "', query, '"')
        if connection:
            title = string_concat(title, ' using "', connection,
                                  '" connection')
        context = {
            'results':
            self.get_wrapped_search_results(page.object_list),
            'pagination_required':
            page.has_other_pages(),
            'page_range':
            paginator.page_range,
            'page_num':
            page.number,
            'result_count':
            paginator.count,
            'opts':
            self.model._meta,
            'title':
            force_unicode(title),
            'root_path':
            getattr(self.admin_site, 'root_path', None),
            'app_label':
            self.model._meta.app_label,
            'filtered':
            True,
            'form':
            form,
            'query_string':
            self.get_current_query_string(request, remove=['p']),
            'search_model_count':
            len(request.GET.getlist('models')),
            'search_facet_count':
            len(request.GET.getlist('possible_facets')),
            'search_var':
            self.get_search_var(request),
            'page_var':
            page_var,
            'facets':
            FacetWrapper(sqs.facet_counts()),
            'module_name':
            force_unicode(self.model._meta.verbose_name_plural),
            'cl':
            FakeChangeListForPaginator(request, page, results_per_page,
                                       self.model._meta),
            'haystack_version':
            _haystack_version,
            # Note: the empty Media object isn't specficially required for the
            # standard Django admin, but is apparently a pre-requisite for
            # things like Grappelli.
            # See #1 (https://github.com/kezabelle/django-haystackbrowser/pull/1)
            'media':
            Media()
        }
        return render_to_response('admin/haystackbrowser/result_list.html',
                                  context,
                                  context_instance=RequestContext(request))
예제 #28
0
    def index(self, request):
        """The view for showing all the results in the Haystack index. Emulates
        the standard Django ChangeList mostly.

        :param request: the current request.
        :type request: WSGIRequest

        :return: A template rendered into an HttpReponse
        """
        if not self.has_change_permission(request, None):
            raise PermissionDenied("Not a superuser")

        page_var = self.get_paginator_var(request)
        form = PreSelectedModelSearchForm(request.GET or None, load_all=False)
        minimum_page = form.fields[page_var].min_value
        # Make sure there are some models indexed
        available_models = model_choices()
        if len(available_models) <= 0:
            raise Search404('No search indexes bound via Haystack')

        # We've not selected any models, so we're going to redirect and select
        # all of them. This will bite me in the ass if someone searches for a string
        # but no models, but I don't know WTF they'd expect to return, anyway.
        # Note that I'm only doing this to sidestep this issue:
        # https://gist.github.com/3766607
        if 'models' not in request.GET.keys():
            # TODO: make this betterererer.
            new_qs = ['&models=%s' % x[0] for x in available_models]
            # if we're in haystack2, we probably want to provide the 'default'
            # connection so that it behaves as if "initial" were in place.
            if form.has_multiple_connections():
                new_qs.append('&connection=' + form.fields['connection'].initial)
            new_qs = ''.join(new_qs)
            existing_query = request.GET.copy()
            if page_var in existing_query:
                existing_query.pop(page_var)
            existing_query[page_var] = minimum_page
            location = '%(path)s?%(existing_qs)s%(new_qs)s' % {
                'existing_qs': existing_query.urlencode(),
                'new_qs': new_qs,
                'path': request.path_info,
            }
            return HttpResponseRedirect(location)

        sqs = form.search()
        cleaned_GET = form.cleaned_data_querydict
        try:
            page_no = int(cleaned_GET.get(PAGE_VAR, minimum_page))
        except ValueError:
            page_no = minimum_page
        results_per_page = self.get_results_per_page(request)
        paginator = Paginator(sqs, results_per_page)
        try:
            page = paginator.page(page_no+1)
        except (InvalidPage, ValueError):
            # paginator.page may raise InvalidPage if we've gone too far
            # meanwhile, casting the querystring parameter may raise ValueError
            # if it's None, or '', or other silly input.
            raise Search404("Invalid page")

        query = request.GET.get(self.get_search_var(request), None)
        connection = request.GET.get('connection', None)
        title = self.model._meta.verbose_name_plural

        wrapped_facets = FacetWrapper(
            sqs.facet_counts(), querydict=form.cleaned_data_querydict.copy())

        context = {
            'results': self.get_wrapped_search_results(page.object_list),
            'pagination_required': page.has_other_pages(),
            # this may be expanded into xrange(*page_range) to copy what
            # the paginator would yield. This prevents 50000+ pages making
            # the page slow to render because of django-debug-toolbar.
            'page_range': (1, paginator.num_pages + 1),
            'page_num': page.number,
            'result_count': paginator.count,
            'opts': self.model._meta,
            'title': force_text(title),
            'root_path': getattr(self.admin_site, 'root_path', None),
            'app_label': self.model._meta.app_label,
            'filtered': True,
            'form': form,
            'form_valid': form.is_valid(),
            'query_string': self.get_current_query_string(request, remove=[page_var]),
            'search_model_count': len(cleaned_GET.getlist('models')),
            'search_facet_count': len(cleaned_GET.getlist('possible_facets')),
            'search_var': self.get_search_var(request),
            'page_var': page_var,
            'facets': wrapped_facets,
            'applied_facets': form.applied_facets(),
            'module_name': force_text(self.model._meta.verbose_name_plural),
            'cl': FakeChangeListForPaginator(request, page, results_per_page, self.model._meta),
            'haystack_version': _haystack_version,
            # Note: the empty Media object isn't specficially required for the
            # standard Django admin, but is apparently a pre-requisite for
            # things like Grappelli.
            # See #1 (https://github.com/kezabelle/django-haystackbrowser/pull/1)
            'media': Media()
        }
        return self.do_render(request=request,
                              template_name='admin/haystackbrowser/result_list.html',
                              context=context)
예제 #29
0
 def test_model_choices(self):
     self.assertEqual(len(model_choices()), 2)
     self.assertEqual([option[1] for option in model_choices()],
                      ['Another mock models', 'Mock models'])
예제 #30
0
    def index(self, request):
        """The view for showing all the results in the Haystack index. Emulates
        the standard Django ChangeList mostly.

        :param request: the current request.
        :type request: WSGIRequest

        :return: A template rendered into an HttpReponse
        """
        page_var = self.get_paginator_var(request)
        form = PreSelectedModelSearchForm(request.GET or None, load_all=False)

        # Make sure there are some models indexed
        available_models = model_choices()
        if len(available_models) <= 0:
            raise Search404("No search indexes bound via Haystack")

        # We've not selected any models, so we're going to redirect and select
        # all of them. This will bite me in the ass if someone searches for a string
        # but no models, but I don't know WTF they'd expect to return, anyway.
        # Note that I'm only doing this to sidestep this issue:
        # https://gist.github.com/3766607
        if "models" not in request.GET.keys():
            # TODO: make this betterererer.
            new_qs = ["&models=%s" % x[0] for x in available_models]
            # if we're in haystack2, we probably want to provide the 'default'
            # connection so that it behaves as if "initial" were in place.
            if form.has_multiple_connections():
                new_qs.append("&connection=" + form.fields["connection"].initial)
            new_qs = "".join(new_qs)
            qs = self.get_current_query_string(request, remove=["p"])
            return HttpResponseRedirect(request.path_info + qs + new_qs)

        try:
            sqs = form.search()
            try:
                page_no = int(request.GET.get(PAGE_VAR, 0))
            except ValueError:
                page_no = 0
            # page_no = int(request.GET.get(page_var, 1))
            results_per_page = self.get_results_per_page(request)
            paginator = Paginator(sqs, results_per_page)
            page = paginator.page(page_no + 1)
        except (InvalidPage, ValueError):
            # paginator.page may raise InvalidPage if we've gone too far
            # meanwhile, casting the querystring parameter may raise ValueError
            # if it's None, or '', or other silly input.
            raise Search404("Invalid page")

        query = request.GET.get(self.get_search_var(request), None)
        connection = request.GET.get("connection", None)
        title = self.model._meta.verbose_name_plural
        if query:
            title = string_concat(self.model._meta.verbose_name_plural, ' for "', query, '"')
        if connection:
            title = string_concat(title, ' using "', connection, '" connection')
        context = {
            "results": self.get_wrapped_search_results(page.object_list),
            "pagination_required": page.has_other_pages(),
            # this may be expanded into xrange(*page_range) to copy what
            # the paginator would yield. This prevents 50000+ pages making
            # the page slow to render because of django-debug-toolbar.
            "page_range": (1, paginator.num_pages + 1),
            "page_num": page.number,
            "result_count": paginator.count,
            "opts": self.model._meta,
            "title": force_text(title),
            "root_path": getattr(self.admin_site, "root_path", None),
            "app_label": self.model._meta.app_label,
            "filtered": True,
            "form": form,
            "query_string": self.get_current_query_string(request, remove=["p"]),
            "search_model_count": len(request.GET.getlist("models")),
            "search_facet_count": len(request.GET.getlist("possible_facets")),
            "search_var": self.get_search_var(request),
            "page_var": page_var,
            "facets": FacetWrapper(sqs.facet_counts()),
            "module_name": force_text(self.model._meta.verbose_name_plural),
            "cl": FakeChangeListForPaginator(request, page, results_per_page, self.model._meta),
            "haystack_version": _haystack_version,
            # Note: the empty Media object isn't specficially required for the
            # standard Django admin, but is apparently a pre-requisite for
            # things like Grappelli.
            # See #1 (https://github.com/kezabelle/django-haystackbrowser/pull/1)
            "media": Media(),
        }
        return render_to_response(
            "admin/haystackbrowser/result_list.html", context, context_instance=RequestContext(request)
        )
예제 #31
0
파일: forms.py 프로젝트: hgw/rhizome.org
 def __init__(self, *args, **kwargs):
     super(RhizomeModelSearchForm, self).__init__(*args, **kwargs)
     self.fields["models"] = forms.MultipleChoiceField(
         choices=model_choices(), required=False, label=_("Search In"), widget=SearchCheckboxSelectMultiple
     )
예제 #32
0
 def __init__(self, *args, **kwargs):
     super(AdvModelSearchForm, self).__init__(*args, **kwargs)
     self.fields['models'] = forms.MultipleChoiceField(choices=model_choices(), required=False, label='Limit Search To:', widget=forms.SelectMultiple)
예제 #33
0
 def test_model_choices(self):
     self.assertEqual(len(model_choices()), 2)
     self.assertEqual(
         [option[1] for option in model_choices()],
         ["Another mock models", "Mock models"],
     )
예제 #34
0
파일: forms.py 프로젝트: K-DOT/it_blog
 def __init__(self, *args, **kwargs):
     super(OneModelSearchForm, self).__init__(*args, **kwargs)
     self.fields['models'] = forms.ChoiceField(initial='blog.post', choices=model_choices(), required=False, label='Search In',)
예제 #35
0
def override_model_choices(site=None):
    choices = model_choices(site=site)
    new_choices = []
    for k, v in choices:
        new_choices.append((k, overrides.get(k, v)))
    return sorted(new_choices, key=lambda x: x[1])