Exemple #1
0
class PublishersView(SearchView):
    paginate_by = NB_RESULTS_PER_PAGE
    template_name = 'publishers/list.html'
    form_class = PublisherForm
    queryset = SearchQuerySet().models(Publisher)

    def get_form_kwargs(self):
        """
        We make sure the search is valid even if no parameter
        was passed, in which case we add a default empty query.
        Otherwise the search form is not bound and search fails.
        """
        args = super(PublishersView, self).get_form_kwargs()
        if 'data' not in args:
            args['data'] = {self.search_field: ''}
        return args

    def get_context_data(self, **kwargs):
        context = super(PublishersView, self).get_context_data(**kwargs)

        context['search_description'] = _('Publishers')
        context['nb_results'] = self.queryset.count()
        context['breadcrumbs'] = publishers_breadcrumbs()
        context['oa_desc'] = dict([(s[0], s[2]) for s in OA_STATUS_CHOICES])

        return context
Exemple #2
0
 def update_stats(self):
     if not self.stats:
         self.stats = AccessStatistics.objects.create()
         self.save()
     from papers.models import Paper
     sqs = SearchQuerySet().models(Paper).filter(journal=self.id)
     self.stats.update_from_search_queryset(sqs)
Exemple #3
0
    def link_existing_papers(self, researcher):
        """
        Search for papers which bear the ORCID id of the researcher,
        but which are not linked to the researcher itself, and updates them
        to link to the researcher.
        """
        queryset = SearchQuerySet().models(Paper).filter(
            orcids=researcher.orcid).load_all()
        papers_to_update = []
        for search_result in queryset:
            paper = search_result.object
            if researcher.id not in paper.researcher_ids:
                new_authors = paper.authors
                for author in new_authors:
                    if author.orcid == researcher.orcid:
                        author.researcher_id = researcher.id
                paper.authors_list = [
                    author.serialize() for author in new_authors
                ]
                papers_to_update.append(paper)
                paper.update_index()

        if papers_to_update:
            Paper.objects.bulk_update(papers_to_update, ['authors_list'])
Exemple #4
0
class PaperSearchView(SearchView):
    """Displays a list of papers and a search form."""

    paginate_by = NB_RESULTS_PER_PAGE
    template_name = 'papers/search.html'
    form_class = PaperSearchForm
    queryset = SearchQuerySet().models(Paper)

    def get(self, request, *args, **kwargs):
        """
        If the user is no admin, we remove visivle, availability and oa_status GET statements
        """
        if not is_admin(request.user):
            request.GET = request.GET.copy()
            request.GET.pop('visible', None)
            request.GET.pop('availability', None)
            request.GET.pop('oa_status', None)

        return super().get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        """
        We add some context data.
        """
        context = super().get_context_data(**kwargs)
        search_description = _('Papers')
        query_string = self.request.META.get('QUERY_STRING', '')
        context['breadcrumbs'] = [(search_description, '')]
        context[
            'search_description'] = search_description if query_string else _(
                'All papers')
        context['search_description_title'] = _('Papers')
        context['nb_results'] = self.queryset.count()
        context['search_stats'] = BareAccessStatistics.from_search_queryset(
            self.queryset)
        context['on_statuses'] = json.dumps(context['form'].on_statuses())

        # Eventually remove sort by parameter
        search_params_without_sort_by = self.request.GET.copy()
        try:
            del search_params_without_sort_by['sort_by']
        except KeyError:
            pass

        # Make a clean URL with useless GET params
        for key in list(search_params_without_sort_by.keys()):
            if not search_params_without_sort_by[key]:
                del search_params_without_sort_by[key]
        context[
            'search_params_without_sort_by'] = search_params_without_sort_by.urlencode(
            )

        # Get current sort_by value
        current_sort_by_value = self.request.GET.get('sort_by', None)
        try:
            current_sort_by = next(v for k, v in self.form_class.SORT_CHOICES
                                   if k == current_sort_by_value)
        except StopIteration:
            current_sort_by = self.form_class.SORT_CHOICES[0][1]
        context['current_sort_by'] = current_sort_by

        # Notifications
        if self.request.user.is_authenticated:
            context['messages'] = Notification.objects.filter(
                inbox__user=self.request.user).order_by('-date')[:3]

        return context

    def get_form_kwargs(self):
        """
        We make sure the search is valid even if no parameter
        was passed, in which case we add a default empty query.
        Otherwise the search form is not bound and search fails.
        """
        args = super().get_form_kwargs()

        if 'data' not in args:
            args['data'] = {self.search_field: ''}

        return args

    def render_to_response(self, context, **kwargs):
        """
        If JSON is requested, we deliver JSON, else normal HTML
        """
        if self.request.META.get('CONTENT_TYPE') == 'application/json':
            data = self.raw_response(context, **kwargs)
            response = HttpResponse(json.dumps(data),
                                    content_type='application/json')
            # Chrome has agressive caching and caches XHttpResponses as well which bites with manipulation of browser history, so tell not to cache.
            add_never_cache_headers(response)
            return response
        return super().render_to_response(context, **kwargs)

    def raw_response(self, context, **kwargs):
        """
        A raw response, containing meta information and some HTML
        """
        context['request'] = self.request
        listPapers = loader.render_to_string('papers/paper_list.html', context)
        messages = loader.render_to_string('papers/messages.html', context)
        stats = context['search_stats'].pie_data()
        stats['on_statuses'] = context['form'].on_statuses()
        return {
            'listPapers': listPapers,
            'messages': messages,
            'stats': stats,
            'nb_results': context['nb_results'],
        }

    def url_with_query_string(self, url=None, query_string=None):
        """
        Returns the current URL with its query string.

        Both the URL and the query string can be overriden.
        """
        url = url or escape_uri_path(self.request.path)
        if query_string is None:
            query_string = self.request.META.get('QUERY_STRING', '')
        if query_string:
            url += '?' + query_string
        return url
Exemple #5
0
class PaperSearchView(SearchView):
    """Displays a list of papers and a search form."""

    paginate_by = NB_RESULTS_PER_PAGE
    template_name = 'papers/search.html'
    form_class = PaperForm
    queryset = SearchQuerySet().models(Paper)

    def get(self, request, *args, **kwargs):
        if not is_admin(request.user):
            request.GET = request.GET.copy()
            request.GET.pop('visible', None)
            request.GET.pop('availability', None)
            request.GET.pop('oa_status', None)

        return super(PaperSearchView, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(PaperSearchView, self).get_context_data(**kwargs)
        search_description = _('Papers')
        query_string = self.request.META.get('QUERY_STRING', '')
        context['breadcrumbs'] = [(search_description, '')]
        context['search_description'] = (search_description
                                         if query_string else _('All papers'))
        context['head_search_description'] = _('Papers')
        context['nb_results'] = self.queryset.count()
        context['search_stats'] = BareAccessStatistics.from_search_queryset(
            self.queryset)
        context['on_statuses'] = json.dumps(context['form'].on_statuses())
        context['ajax_url'] = reverse('ajax-search')

        # Eventually remove sort by parameter
        search_params_without_sort_by = self.request.GET.copy()
        try:
            del search_params_without_sort_by['sort_by']
        except KeyError:
            pass
        # Make a clean URL with useless GET params
        for key in list(search_params_without_sort_by.keys()):
            if not search_params_without_sort_by[key]:
                del search_params_without_sort_by[key]
        context['search_params_without_sort_by'] = (
            search_params_without_sort_by.urlencode())
        # Get current sort_by value
        current_sort_by_value = self.request.GET.get('sort_by', None)
        try:
            current_sort_by = next(v for k, v in self.form_class.SORT_CHOICES
                                   if k == current_sort_by_value)
        except StopIteration:
            current_sort_by = self.form_class.SORT_CHOICES[0][1]
        context['current_sort_by'] = current_sort_by

        # Notifications
        # TODO: unefficient query.
        notifications = get_notifications(self.request)
        selected_messages = [
            n.serialize_to_json()
            for n in sorted(notifications, key=lambda msg: msg.level)[:3]
        ]
        context['messages'] = selected_messages

        return context

    def get_form_kwargs(self):
        """
        We make sure the search is valid even if no parameter
        was passed, in which case we add a default empty query.
        Otherwise the search form is not bound and search fails.
        """
        args = super(PaperSearchView, self).get_form_kwargs()

        if 'data' not in args:
            args['data'] = {self.search_field: ''}

        return args

    def render_to_response(self, context, **kwargs):
        if self.request.META.get('CONTENT_TYPE') == 'application/json':
            response = self.raw_response(context, **kwargs)
            return HttpResponse(json.dumps(response),
                                content_type='application/json')
        return super(PaperSearchView, self)\
            .render_to_response(context, **kwargs)

    def raw_response(self, context, **kwargs):
        context['request'] = self.request
        listPapers = loader.render_to_string('papers/paperList.html', context)
        stats = context['search_stats'].pie_data()
        stats['on_statuses'] = context['form'].on_statuses()
        return {
            'listPapers': listPapers,
            'messages': context['messages'],
            'stats': stats,
            'nb_results': context['nb_results'],
        }

    def url_with_query_string(self, url=None, query_string=None):
        """
        Returns the current URL with its query string.

        Both the URL and the query string can be overriden.
        """
        url = url or escape_uri_path(self.request.path)
        if query_string is None:
            query_string = self.request.META.get('QUERY_STRING', '')
        if query_string:
            url += '?' + query_string
        return url