예제 #1
0
    def get_items(self):
        """ Return the (object_list, extra_context) for this request."""
        year = self.get_year()
        month = self.get_month()

        date_field_start = self.get_date_field_start()
        date_field_end = self.get_date_field_end()

        date = _date_from_string(year, self.get_year_format(), month,
                                 self.get_month_format())

        since = self._make_date_lookup_arg(date)
        until = self._make_date_lookup_arg(self._get_next_month(date))

        # Query for items that either start or end during the given month
        lookup_args = (Q(**{'{}__gte'.format(df): since})
                       & Q(**{'{}__lt'.format(df): until})
                       for df in (date_field_start, date_field_end))

        lookup_args = functools.reduce(Q.__or__, lookup_args)

        qs = self.get_dated_queryset(lookup_args)

        return (qs, {
            'month': date,
            'next_month': self.get_next_month(date),
            'previous_month': self.get_previous_month(date),
        })
예제 #2
0
    def get_object(self, queryset=None):

        year = self.get_year()
        month = self.get_month()
        date = _date_from_string(
            year, self.get_year_format(),
            month, self.get_month_format(),
            )
        
        if queryset is None:
            queryset = self.get_queryset()
        if (not self.get_allow_future()
            and date > date.today()):
            
            raise Http404(
                "Future {} not available because"
                "{}.allow_future is False."
                .format(
                    (queryset.model
                     ._meta.verbose_name_plural),
                    self.__class__.__name__))
        filter_dict = (
            self._make_single_date_lookup(date))
        queryset = queryset.filter(**filter_dict)
        return super().get_object(
            queryset=queryset)
예제 #3
0
    def get_dated_items(self):
        """
        Return (date_list, items, extra_context) for this request.
        """
        year = self.get_year()
        month = self.get_month()
        date = _date_from_string(year, self.get_year_format(), month,
                                 self.get_month_format())

        since = _make_date_lookup(date)
        if date.month == 12:
            until = _make_date_lookup(datetime.date(date.year + 1, 1, 1))
        else:
            until = _make_date_lookup(
                datetime.date(date.year, date.month + 1, 1))
        lookup_kwargs = {
            'creation_date__gte': since,
            'creation_date__lt': until,
        }

        qs = self.get_dated_queryset(**lookup_kwargs)
        date_list = self.get_date_list(qs, 'day')

        return (date_list, qs, {
            'month': date,
            'next_month': self.get_next_month(date),
            'previous_month': self.get_previous_month(date),
        })
예제 #4
0
    def get_object(self, queryset=None):
        year = self.get_year()
        month = self.get_month()
        day = self.get_day()
        self.date = _date_from_string(year, self.get_year_format(),
                                      month, self.get_month_format(),
                                      day, self.get_day_format())

        # Use a custom queryset if provided
        qs = queryset or self.get_queryset()

        if not self.get_allow_future() and self.date > now().date():
            raise Http404(_(u"Future %(verbose_name_plural)s not available because %(class_name)s.allow_future is False.") % {
                'verbose_name_plural': qs.model._meta.verbose_name_plural,
                'class_name': self.__class__.__name__,
            })

        # Filter down a queryset from self.queryset using the date from the
        # URL. This'll get passed as the queryset to DetailView.get_object,
        # which'll handle the 404
        date_field = self.get_date_field()
        field = qs.model._meta.get_field(date_field)
        if DJANGO_VERSION[0:2] < (1, 5):
            lookup = _date_lookup_for_field(field, self.date)
        else:
            lookup = self._make_single_date_lookup(field)
        qs = qs.filter(**lookup)
        for diarydetail in qs:
            for entry in diarydetail.detail.published():
                entry.visits = F('visits') + 1
                entry.save()
        return qs.get()
예제 #5
0
 def get_date(self):
     return _date_from_string(
         self.get_year(),
         self.get_year_format(),
         self.get_month(),
         self.get_month_format(),
     )
예제 #6
0
파일: views.py 프로젝트: artemzi/pepysdiary
    def get_next_previous(self):
        """
        Get the next/previous Entries based on the current Entry's date.
        """
        year = self.get_year()
        month = self.get_month()
        day = self.get_day()

        date = _date_from_string(year, self.get_year_format(), month,
                                 self.get_month_format(), day,
                                 self.get_day_format())

        try:
            previous_entry = self.model.objects.filter(
                diary_date__lt=date).order_by('-diary_date')[:1].get()
        except self.model.DoesNotExist:
            previous_entry = None

        try:
            next_entry = self.model.objects.filter(
                diary_date__gt=date).order_by('diary_date')[:1].get()
        except self.model.DoesNotExist:
            next_entry = None

        return {
            'previous_entry': previous_entry,
            'next_entry': next_entry,
        }
예제 #7
0
    def get_object(self, queryset=None):
        year = self.get_year()
        month = self.get_month()
        day = self.get_day()
        self.date = _date_from_string(year, self.get_year_format(), month,
                                      self.get_month_format(), day,
                                      self.get_day_format())

        # Use a custom queryset if provided
        qs = queryset or self.get_queryset()

        if not self.get_allow_future() and self.date > now().date():
            raise Http404(
                _(u"Future %(verbose_name_plural)s not available because %(class_name)s.allow_future is False."
                  ) %
                {
                    'verbose_name_plural': qs.model._meta.verbose_name_plural,
                    'class_name': self.__class__.__name__,
                })

        # Filter down a queryset from self.queryset using the date from the
        # URL. This'll get passed as the queryset to DetailView.get_object,
        # which'll handle the 404
        date_field = self.get_date_field()
        field = qs.model._meta.get_field(date_field)
        if DJANGO_VERSION[0:2] < (1, 5):
            lookup = _date_lookup_for_field(field, self.date)
        else:
            lookup = self._make_single_date_lookup(field)
        qs = qs.filter(**lookup)
        for diarydetail in qs:
            for entry in diarydetail.detail.published():
                entry.visits = F('visits') + 1
                entry.save()
        return qs.get()
예제 #8
0
    def get_object(self, queryset=None):
        """
        Get the object this request displays.
        """
        year = self.get_year()
        month = self.get_month()
        day = self.get_day()
        date = _date_from_string(year, self.get_year_format(), month,
                                 self.get_month_format(), day,
                                 self.get_day_format())

        if queryset is None:
            queryset = self.get_queryset()

        if not self.get_allow_future(
        ) and date > datetime.date.today():  # pragma: no cover
            raise Http404(
                _(u"Future %(verbose_name_plural)s not available because %(class_name)s.allow_future is False."
                  ) % {
                      'verbose_name_plural':
                      queryset.model._meta.verbose_name_plural,
                      'class_name': self.__class__.__name__,
                  })

        # Filter down a queryset from self.queryset using the date from the
        # URL. This'll get passed as the queryset to DetailView.get_object,
        # which'll handle the 404
        date_field = self.get_date_field()
        field = queryset.model._meta.get_field(date_field)
        lookup = _date_lookup_for_field(field, date)
        queryset = queryset.filter(**lookup)

        return super(BaseDateDetailView, self).get_object(queryset=queryset)
예제 #9
0
    def get_dated_items(self):
        """
        Return (date_list, items, extra_context) for this request.
        """
        year = self.get_year()
        month = self.get_month()
        date = _date_from_string(year, self.get_year_format(),
                                 month, self.get_month_format())

        since = _make_date_lookup(date)
        if date.month == 12:
            until = _make_date_lookup(
                datetime.date(date.year + 1, 1, 1))
        else:
            until = _make_date_lookup(
                datetime.date(date.year, date.month + 1, 1))
        lookup_kwargs = {
            'creation_date__gte': since,
            'creation_date__lt': until}

        qs = self.get_dated_queryset(**lookup_kwargs)
        date_list = self.get_date_list(qs, 'day')

        return (date_list, qs, {
            'month': date,
            'next_month': self.get_next_month(date),
            'previous_month': self.get_previous_month(date)})
예제 #10
0
    def get_object(self, queryset=None):
        """
        Get the object this request displays.
        """
        year = self.get_year()
        month = self.get_month()
        day = self.get_day()
        date = _date_from_string(year, self.get_year_format(),
                                 month, self.get_month_format(),
                                 day, self.get_day_format())

        if queryset is None:
            queryset = self.get_queryset()

        if not self.get_allow_future() and date > datetime.date.today(): # pragma: no cover
            raise Http404(_(u"Future %(verbose_name_plural)s not available because %(class_name)s.allow_future is False.") % {
                'verbose_name_plural': queryset.model._meta.verbose_name_plural,
                'class_name': self.__class__.__name__,
            })

        # Filter down a queryset from self.queryset using the date from the
        # URL. This'll get passed as the queryset to DetailView.get_object,
        # which'll handle the 404
        date_field = self.get_date_field()
        field = queryset.model._meta.get_field(date_field)
        lookup = _date_lookup_for_field(field, date)
        queryset = queryset.filter(**lookup)

        return super(BaseDateDetailView, self).get_object(queryset=queryset)
예제 #11
0
    def get_dated_items(self):
        """
        Return (date_list, items, extra_context) for this request.
        """
        year = self.get_year()
        week = self.get_week()
        date_field = self.get_date_field()
        week_format = self.get_week_format()
        week_start = {
            '%W': '1',
            '%U': '0',
        }[week_format]
        date = _date_from_string(year, self.get_year_format(),
                            week_start, '%w',
                            week, week_format)
        since = self._make_date_lookup_arg(date)
        until = self._make_date_lookup_arg(self._get_next_week(date))

        # Patched To allow FK date_field
        if self.fk_date_field:
            date_field = self.fk_date_field

        lookup_kwargs = {
            '%s__gte' % date_field: since,
            '%s__lt' % date_field: until,
        }
        qs = self.get_dated_queryset(**lookup_kwargs)
        return (None, qs, {
            'week': date,
            'next_week': self.get_next_week(date),
            'previous_week': self.get_previous_week(date),
        })
예제 #12
0
    def get_object(self, queryset=None):
        """
        Get the object this request displays.
        """
        year = self.get_year()
        month = self.get_month()
        day = self.get_day()
        date = _date_from_string(year, self.get_year_format(),
                                 month, self.get_month_format(),
                                 day, self.get_day_format())

        # Use a custom queryset if provided
        qs = self.get_queryset() if queryset is None else queryset

        if not self.get_allow_future() and date > datetime.date.today():
            raise Http404(_(
                "Future %(verbose_name_plural)s not available because "
                "%(class_name)s.allow_future is False.") % {
                'verbose_name_plural': qs.model._meta.verbose_name_plural,
                'class_name': self.__class__.__name__,
                },
            )

        # Filter down a queryset from self.queryset using the date from the
        # URL. This'll get passed as the queryset to DetailView.get_object,
        # which'll handle the 404
        lookup_kwargs = self._make_single_date_lookup(date)
        qs = qs.filter(**lookup_kwargs)

        return super(PostView, self).get_object(queryset=qs)
예제 #13
0
    def get_next_previous(self):
        """
        Get the next/previous Entries based on the current Entry's date.
        """
        year = self.get_year()
        month = self.get_month()
        day = self.get_day()

        date = _date_from_string(year, self.get_year_format(),
                                 month, self.get_month_format(),
                                 day, self.get_day_format())

        try:
            previous_entry = self.model.objects.filter(
                        diary_date__lt=date).order_by('-diary_date')[:1].get()
        except self.model.DoesNotExist:
            previous_entry = None

        try:
            next_entry = self.model.objects.filter(
                        diary_date__gt=date).order_by('diary_date')[:1].get()
        except self.model.DoesNotExist:
            next_entry = None

        return {
            'previous_entry': previous_entry,
            'next_entry': next_entry,
        }
예제 #14
0
    def get_queryset(self):
        qs = super(BaseCalendarMonthView, self).get_queryset()

        year = self.get_year()
        month = self.get_month()

        date_field = self.get_date_field()
        end_date_field = self.get_end_date_field()

        date = _date_from_string(year, self.get_year_format(),
                                 month, self.get_month_format())

        since = date
        until = self.get_next_month(date)

        # Adjust our start and end dates to allow for next and previous
        # month edges
        if since.weekday() != self.get_first_of_week():
            diff = math.fabs(since.weekday() - self.get_first_of_week())
            since = since - datetime.timedelta(days=diff)

        if until.weekday() != ((self.get_first_of_week() + 6) % 7):
            diff = math.fabs(((self.get_first_of_week() + 6) % 7) - until.weekday())
            until = until + datetime.timedelta(days=diff)

        if end_date_field:
            # 5 possible conditions for showing an event:

            # 1) Single day event, starts after 'since'
            # 2) Multi-day event, starts after 'since' and ends before 'until'
            # 3) Starts before 'since' and ends after 'since' and before 'until'
            # 4) Starts after 'since' but before 'until' and ends after 'until'
            # 5) Starts before 'since' and ends after 'until'
            predicate1 = Q(**{
                '%s__gte' % date_field: since,
                end_date_field: None
            })
            predicate2 = Q(**{
                '%s__gte' % date_field: since,
                '%s__lt' % end_date_field: until
            })
            predicate3 = Q(**{
                '%s__lt' % date_field: since,
                '%s__gte' % end_date_field: since,
                '%s__lt' % end_date_field: until
            })
            predicate4 = Q(**{
                '%s__gte' % date_field: since,
                '%s__lt' % date_field: until,
                '%s__gte' % end_date_field: until
            })
            predicate5 = Q(**{
                '%s__lt' % date_field: since,
                '%s__gte' % end_date_field: until
            })
            return qs.filter(predicate1 | predicate2 | predicate3| predicate4 | predicate5)
        return qs.filter(**{
            '%s__gte' % date_field: since
        })
예제 #15
0
    def get_object(self, queryset=None):
        """
        Compat for django 1.4
        """
        # Django >= 1.5
        if hasattr(dates.DateDetailView, '_make_date_lookup_arg'):
            return super(dates.DateDetailView, self).get_object(queryset)

        def _date_lookup_for_field(field, date):
            """
            Patch the function so it returns aware datetimes using UTC.
            """
            if isinstance(field, models.DateTimeField):
                date_range = (
                    timezone.make_aware(
                        datetime.datetime.combine(date, datetime.time.min),
                        timezone.utc),
                    timezone.make_aware(
                        datetime.datetime.combine(date, datetime.time.max),
                        timezone.utc)
                )
                return {'%s__range' % field.name: date_range}
            else:
                return {field.name: date}

        year = self.get_year()
        month = self.get_month()
        day = self.get_day()
        date = dates._date_from_string(
            year, self.get_year_format(),
            month, self.get_month_format(),
            day, self.get_day_format())

        # Use a custom queryset if provided
        qs = queryset or self.get_queryset()

        if not self.get_allow_future() and date > datetime.date.today():
            raise Http404(_(
                "Future %(verbose_name_plural)s not available"
                " because %(class_name)s.allow_future is False.") % {
                'verbose_name_plural': qs.model._meta.verbose_name_plural,
                'class_name': self.__class__.__name__,
            })

        # Filter down a queryset from self.queryset using the date from the
        # URL. This'll get passed as the queryset to DetailView.get_object,
        # which'll handle the 404
        date_field = self.get_date_field()
        field = qs.model._meta.get_field(date_field)

        if settings.USE_TZ:
            lookup = _date_lookup_for_field(field, date)
        else:
            lookup = dates._date_lookup_for_field(field, date)

        qs = qs.filter(**lookup)

        return super(dates.BaseDetailView, self).get_object(queryset=qs)
예제 #16
0
    def get_object(self, queryset=None):
        """
        Compat for django 1.4
        """
        # Django >= 1.5
        if hasattr(dates.DateDetailView, '_make_date_lookup_arg'):
            return super(dates.DateDetailView, self).get_object(queryset)

        def _date_lookup_for_field(field, date):
            """
            Patch the function so it returns aware datetimes using UTC.
            """
            if isinstance(field, models.DateTimeField):
                date_range = (timezone.make_aware(
                    datetime.datetime.combine(date, datetime.time.min),
                    timezone.utc),
                              timezone.make_aware(
                                  datetime.datetime.combine(
                                      date, datetime.time.max), timezone.utc))
                return {'%s__range' % field.name: date_range}
            else:
                return {field.name: date}

        year = self.get_year()
        month = self.get_month()
        day = self.get_day()
        date = dates._date_from_string(year, self.get_year_format(), month,
                                       self.get_month_format(), day,
                                       self.get_day_format())

        # Use a custom queryset if provided
        qs = queryset or self.get_queryset()

        if not self.get_allow_future() and date > datetime.date.today():
            raise Http404(
                _(u"Future %(verbose_name_plural)s not available because %(class_name)s.allow_future is False."
                  ) %
                {
                    'verbose_name_plural': qs.model._meta.verbose_name_plural,
                    'class_name': self.__class__.__name__,
                })

        # Filter down a queryset from self.queryset using the date from the
        # URL. This'll get passed as the queryset to DetailView.get_object,
        # which'll handle the 404
        date_field = self.get_date_field()
        field = qs.model._meta.get_field(date_field)

        if settings.USE_TZ:
            lookup = _date_lookup_for_field(field, date)
        else:
            lookup = dates._date_lookup_for_field(field, date)

        qs = qs.filter(**lookup)

        return super(dates.BaseDetailView, self).get_object(queryset=qs)
예제 #17
0
 def __get_date(self):
     year = self.get_year()
     week = self.get_week()
     week_format = self.get_week_format()
     week_start = {
         '%W': '1',
         '%U': '0',
     }[week_format]
     return _date_from_string(year, self.get_year_format(), week_start, '%w',
                              week, week_format)
예제 #18
0
파일: views.py 프로젝트: pystars/bumerang
 def get_date(self):
     try:
         year = self.get_year()
         month = self.get_month()
         day = self.get_day()
         return _date_from_string(
             year, self.get_year_format(),
             month, self.get_month_format(),
             day, self.get_day_format())
     except Http404:
         return date.today()
예제 #19
0
    def get_date(self):
        """
        Return (date_list, items, extra_context) for this request.
        """
        year = self.get_year()
        month = self.get_month()
        day = self.get_day()

        return _date_from_string(year, self.get_year_format(), month,
                                 self.get_month_format(), day,
                                 self.get_day_format())
예제 #20
0
파일: views.py 프로젝트: NavyaEV/instagram
    def get_date(self):
        """
        Return (date_list, items, extra_context) for this request.
        """
        year = self.get_year()
        month = self.get_month()
        day = self.get_day()

        return _date_from_string(year, self.get_year_format(),
                                 month, self.get_month_format(),
                                 day, self.get_day_format())
예제 #21
0
    def get_object(self):
        year = self.get_year()
        month = self.get_month()
        day = self.get_day()
        date = _date_from_string(year, self.get_year_format(),
                                 month, self.get_month_format(),
                                 day, self.get_day_format())

        return self.get_queryset().filter(
            publish__year=date.year,
            publish__month=date.month,
            publish__day=date.day
        ).get(slug=self.kwargs['slug'])
예제 #22
0
 def get_object(self, queryset=None):
     """
     Get the object this request displays.
     """
     year = self.get_year()
     month = self.get_month()
     day = self.get_day()
     date = _date_from_string(year, self.get_year_format(),
                              month, self.get_month_format(),
                              day, self.get_day_format())
     qs = queryset or self.get_queryset()
     lookup = _date_lookup_for_field(date)
     qs = qs.filter(**lookup)
     return super(BaseDetailView, self).get_object(queryset=qs)
예제 #23
0
 def get_object(self, queryset=None):
     """
     Get the object this request displays.
     """
     year = self.get_year()
     month = self.get_month()
     day = self.get_day()
     date = _date_from_string(year, self.get_year_format(), month,
                              self.get_month_format(), day,
                              self.get_day_format())
     qs = queryset or self.get_queryset()
     lookup = _date_lookup_for_field(date)
     qs = qs.filter(**lookup)
     return super(BaseDetailView, self).get_object(queryset=qs)
예제 #24
0
파일: views.py 프로젝트: artemzi/pepysdiary
    def get_object(self, queryset=None):
        """
        Get the object this request displays.
        This is mainly just overriding DateDetailView's get_object() method
        with the change that we don't call DetailView's get_object() method
        at the end, because we don't need a slug or pk.
        """
        year = self.get_year()
        month = self.get_month()
        day = self.get_day()
        date = _date_from_string(year, self.get_year_format(), month,
                                 self.get_month_format(), day,
                                 self.get_day_format())

        # Use a custom queryset if provided
        qs = queryset or self.get_queryset()

        if not self.get_allow_future() and date > datetime.date.today():
            raise Http404(
                _(u"Future %(verbose_name_plural)s not available because %(class_name)s.allow_future is False."
                  ) %
                {
                    'verbose_name_plural': qs.model._meta.verbose_name_plural,
                    'class_name': self.__class__.__name__,
                })

        # Filter down a queryset from self.queryset using the date from the
        # URL. This'll get passed as the queryset to DetailView.get_object,
        # which'll handle the 404
        # date_field = self.get_date_field()
        # field = qs.model._meta.get_field(date_field)
        # lookup = _date_lookup_for_field(field, date)
        lookup_kwargs = self._make_single_date_lookup(date)
        qs = qs.filter(**lookup_kwargs)

        # Here's where we differ from DateDetailView.get_object().
        # Instead of calling DetailView.get_object(), we just fetch an object
        # based on the date we've got.
        try:
            obj = qs.get()
        except ObjectDoesNotExist:
            raise Http404(
                _(u"No %(verbose_name)s found matching the query") %
                {'verbose_name': qs.model._meta.verbose_name})
        return obj
예제 #25
0
    def get_object(self, queryset=None):
        year = self.get_year()
        month = self.get_month()
        day = self.get_day()
        date = _date_from_string(year, self.get_year_format(),
            month, self.get_month_format(),
            day, self.get_day_format())

        # Use a custom queryset if provided
        qs = queryset or self.get_queryset()

        if not self.get_allow_future() and date > datetime.date.today():
            raise Http404(_(u"""Future %(verbose_name_plural)s not available
             because %(class_name)s.allow_future is False.""") % {
                'verbose_name_plural': qs.model._meta.verbose_name_plural,
                'class_name': self.__class__.__name__,
                })

        return self.get_playlist_by_date(qs, date)
예제 #26
0
    def get_dated_items(self):
        """
        Return (date_list, items, extra_context) for this request.
        """
        year = self.get_year()
        week = self.get_week()
        week_format = self.get_week_format()
        week_start = {'%W': '1', '%U': '0'}[week_format]
        date = _date_from_string(year, self.get_year_format(),
                                 week_start, '%w',
                                 week, week_format)
        since = _make_date_lookup(date)
        until = _make_date_lookup(date + datetime.timedelta(days=7))
        lookup_kwargs = {
            'creation_date__gte': since,
            'creation_date__lt': until}

        qs = self.get_dated_queryset(**lookup_kwargs)

        return (None, qs, {'week': date})
예제 #27
0
    def get_object(self, queryset=None):
        """
        Get the object this request displays.
        This is mainly just overriding DateDetailView's get_object() method
        with the change that we don't call DetailView's get_object() method
        at the end, because we don't need a slug or pk.
        """
        year = self.get_year()
        month = self.get_month()
        day = self.get_day()
        date = _date_from_string(year, self.get_year_format(),
                                 month, self.get_month_format(),
                                 day, self.get_day_format())

        # Use a custom queryset if provided
        qs = queryset or self.get_queryset()

        if not self.get_allow_future() and date > datetime.date.today():
            raise Http404(_("Future %(verbose_name_plural)s not available because %(class_name)s.allow_future is False.") % {
                'verbose_name_plural': qs.model._meta.verbose_name_plural,
                'class_name': self.__class__.__name__,
            })

        # Filter down a queryset from self.queryset using the date from the
        # URL. This'll get passed as the queryset to DetailView.get_object,
        # which'll handle the 404
        # date_field = self.get_date_field()
        # field = qs.model._meta.get_field(date_field)
        # lookup = _date_lookup_for_field(field, date)
        lookup_kwargs = self._make_single_date_lookup(date)
        qs = qs.filter(**lookup_kwargs)

        # Here's where we differ from DateDetailView.get_object().
        # Instead of calling DetailView.get_object(), we just fetch an object
        # based on the date we've got.
        try:
            obj = qs.get()
        except ObjectDoesNotExist:
            raise Http404(_("No %(verbose_name)s found matching the query") %
                              {'verbose_name': qs.model._meta.verbose_name})
        return obj
예제 #28
0
    def get_dated_items(self):
        """
        Return (date_list, items, extra_context) for this request.
        """
        year = self.get_year()
        week = self.get_week()
        week_format = self.get_week_format()
        week_start = {
            '%W': '1',
            '%U': '0',
        }[week_format]
        date = _date_from_string(year, self.get_year_format(), week_start,
                                 '%w', week, week_format)
        since = _make_date_lookup(date)
        until = _make_date_lookup(date + datetime.timedelta(days=7))
        lookup_kwargs = {
            'creation_date__gte': since,
            'creation_date__lt': until
        }

        qs = self.get_dated_queryset(**lookup_kwargs)

        return (None, qs, {'week': date})
예제 #29
0
    def get_dated_items(self):
        """ Special dated query, that filters on the foreign key model Point,
        rather than the main model of the queryset User
        """
        # From Base Weekarchiveview
        year = self.get_year()
        week = self.get_week()
        date_field = self.get_date_field()
        week_format = self.get_week_format()
        week_start = {
            '%W': '1',
            '%U': '0',
        }[week_format]
        date = _date_from_string(year, self.get_year_format(),
                                week_start, '%w',
                                week, week_format)
        since = self._make_date_lookup_arg(date)
        until = self._make_date_lookup_arg(self._get_next_week(date))
        period = [since, until]

        # Special Query
        qs = User.objects.select_related('point').all()
        object_list = []

        for i in qs:
            likes = i.point_set\
                .filter(action=Point.TRACK_LIKED, created__range=period)\
                .aggregate(models.Sum('value'))['value__sum']
            dislikes = i.point_set\
                .filter(action=Point.TRACK_DISLIKED, created__range=period)\
                .aggregate(models.Sum('value'))['value__sum']

            likes = likes if (likes != None) else 0
            dislikes = dislikes if (dislikes != None) else 0

            if likes > 0 or dislikes < 0:
                object_list.append({'user': i, 'likes': likes,
                    'dislikes': -1 * dislikes, 'net': likes + dislikes})

        if len(object_list) < 1:
            return (None, object_list, {
                'week': date,
                'next_week': self.get_next_week(date),
                'previous_week': self.get_previous_week(date),
            })


        # Get the highest value
        max_value_net = float(max(object_list, key=lambda i: i['net'])['net'])
        max_value_dis = float(max(object_list, key=lambda i: i['dislikes'])['dislikes'])

        max_value = max(max_value_net, max_value_dis)

        # Find percentage of max value for the week
        for k, v in enumerate(object_list):
            # max is 90 % to give room for arrows
            object_list[k]['dislikes_percent'] = v['dislikes'] / max_value * 90
            object_list[k]['likes_percent'] = v['likes'] / max_value * 90
            object_list[k]['net_percent'] = v['net'] / max_value * 90

        # Return navidational datetime objects as well for traversing other
        # weeks in the template
        return (None, object_list, {
            'week': date,
            'next_week': self.get_next_week(date),
            'previous_week': self.get_previous_week(date),
            'max_value': max_value,
        })
예제 #30
0
    def get_context_data(self, **kwargs):
        """
        Injects variables necessary for rendering the calendar into the context.

        Variables added are: `calendar`, `weekdays`, `month`, `next_month` and
        `previous_month`.
        """
        data = super(BaseCalendarMonthView, self).get_context_data(**kwargs)

        year = self.get_year()
        month = self.get_month()

        date = _date_from_string(year, self.get_year_format(), month,
                                 self.get_month_format())

        cal = Calendar(self.get_first_of_week())

        month_calendar = []
        now = datetime.datetime.utcnow()

        date_lists = defaultdict(list)
        multidate_objs = []

        for obj in data["object_list"]:
            obj_date = self.get_start_date(obj)
            end_date_field = self.get_end_date_field()

            if end_date_field:
                end_date = self.get_end_date(obj)
                if end_date and end_date != obj_date:
                    multidate_objs.append({
                        "obj":
                        obj,
                        "range": [x for x in daterange(obj_date, end_date)],
                    })
                    continue  # We don't put multi-day events in date_lists
            date_lists[obj_date].append(obj)

        for week in cal.monthdatescalendar(date.year, date.month):
            week_range = set(daterange(week[0], week[6]))
            week_events = []

            for val in multidate_objs:
                intersect_length = len(week_range.intersection(val["range"]))

                if intersect_length:
                    # Event happens during this week
                    slot = 1
                    width = (intersect_length
                             )  # How many days is the event during this week?
                    nowrap_previous = (
                        True
                    )  # Does the event continue from the previous week?
                    nowrap_next = True  # Does the event continue to the next week?

                    if val["range"][0] >= week[0]:
                        slot = 1 + (val["range"][0] - week[0]).days
                    else:
                        nowrap_previous = False
                    if val["range"][-1] > week[6]:
                        nowrap_next = False

                    week_events.append({
                        "event": val["obj"],
                        "slot": slot,
                        "width": width,
                        "nowrap_previous": nowrap_previous,
                        "nowrap_next": nowrap_next,
                    })

            week_calendar = {"events": week_events, "date_list": []}
            for day in week:
                week_calendar["date_list"].append({
                    "day":
                    day,
                    "events":
                    date_lists[day],
                    "today":
                    day == now.date(),
                    "is_current_month":
                    day.month == date.month,
                })
            month_calendar.append(week_calendar)

        data["calendar"] = month_calendar
        data["weekdays"] = [DAYS[x] for x in cal.iterweekdays()]
        data["month"] = date
        data["next_month"] = self.get_next_month(date)
        data["previous_month"] = self.get_previous_month(date)

        return data
예제 #31
0
    def get_queryset(self):
        """
        Returns a queryset of models for the month requested
        """
        qs = super(BaseCalendarMonthView, self).get_queryset()

        year = self.get_year()
        month = self.get_month()

        date_field = self.get_date_field()
        end_date_field = self.get_end_date_field()

        date = _date_from_string(year, self.get_year_format(), month,
                                 self.get_month_format())

        since = date
        until = self.get_next_month(date)

        # Adjust our start and end dates to allow for next and previous
        # month edges
        if since.weekday() != self.get_first_of_week():
            diff = math.fabs(since.weekday() - self.get_first_of_week())
            since = since - datetime.timedelta(days=diff)

        if until.weekday() != ((self.get_first_of_week() + 6) % 7):
            diff = math.fabs(((self.get_first_of_week() + 6) % 7) -
                             until.weekday())
            until = until + datetime.timedelta(days=diff)

        if end_date_field:
            # 5 possible conditions for showing an event:

            # 1) Single day event, starts after 'since'
            # 2) Multi-day event, starts after 'since' and ends before 'until'
            # 3) Starts before 'since' and ends after 'since' and before 'until'
            # 4) Starts after 'since' but before 'until' and ends after 'until'
            # 5) Starts before 'since' and ends after 'until'
            predicate1 = Q(**{
                "%s__gte" % date_field: since,
                end_date_field: None
            })
            predicate2 = Q(**{
                "%s__gte" % date_field: since,
                "%s__lt" % end_date_field: until
            })
            predicate3 = Q(
                **{
                    "%s__lt" % date_field: since,
                    "%s__gte" % end_date_field: since,
                    "%s__lt" % end_date_field: until,
                })
            predicate4 = Q(
                **{
                    "%s__gte" % date_field: since,
                    "%s__lt" % date_field: until,
                    "%s__gte" % end_date_field: until,
                })
            predicate5 = Q(**{
                "%s__lt" % date_field: since,
                "%s__gte" % end_date_field: until
            })
            return qs.filter(predicate1 | predicate2 | predicate3 | predicate4
                             | predicate5)
        return qs.filter(**{"%s__gte" % date_field: since})
예제 #32
0
    def get_context_data(self, **kwargs):
        """
        Injects variables necessary for rendering the calendar into the context.

        Variables added are: `calendar`, `weekdays`, `month`, `next_month` and `previous_month`.
        """
        data = super(BaseCalendarMonthView, self).get_context_data(**kwargs)

        year = self.get_year()
        month = self.get_month()

        date = _date_from_string(year, self.get_year_format(),
                                 month, self.get_month_format())

        cal = Calendar(self.get_first_of_week())

        month_calendar = []
        now = datetime.datetime.utcnow()

        date_lists = defaultdict(list)
        multidate_objs = []

        for obj in data['object_list']:
            obj_date = self.get_start_date(obj)
            end_date_field = self.get_end_date_field()

            if end_date_field:
                end_date = self.get_end_date(obj)
                if end_date and end_date != obj_date:
                    multidate_objs.append({
                        'obj': obj,
                        'range': [x for x in daterange(obj_date, end_date)]
                    })
                    continue  # We don't put multi-day events in date_lists
            date_lists[obj_date].append(obj)

        for week in cal.monthdatescalendar(date.year, date.month):
            week_range = set(daterange(week[0], week[6]))
            week_events = []

            for val in multidate_objs:
                intersect_length = len(week_range.intersection(val['range']))

                if intersect_length:
                    # Event happens during this week
                    slot = 1
                    width = intersect_length  # How many days is the event during this week?
                    nowrap_previous = True  # Does the event continue from the previous week?
                    nowrap_next = True  # Does the event continue to the next week?

                    if val['range'][0] >= week[0]:
                        slot = 1 + (val['range'][0] - week[0]).days
                    else:
                        nowrap_previous = False
                    if val['range'][-1] > week[6]:
                        nowrap_next = False

                    week_events.append({
                        'event': val['obj'],
                        'slot': slot,
                        'width': width,
                        'nowrap_previous': nowrap_previous,
                        'nowrap_next': nowrap_next,
                    })

            week_calendar = {
                'events': week_events,
                'date_list': [],
            }
            for day in week:
                week_calendar['date_list'].append({
                    'day': day,
                    'events': date_lists[day],
                    'today': day == now.date(),
                    'is_current_month': day.month == date.month,
                })
            month_calendar.append(week_calendar)

        data['calendar'] = month_calendar
        data['weekdays'] = [DAYS[x] for x in cal.iterweekdays()]
        data['month'] = date
        data['next_month'] = self.get_next_month(date)
        data['previous_month'] = self.get_previous_month(date)

        return data
예제 #33
0
파일: streams.py 프로젝트: danjac/localhub
def timeline_view(request):

    current_year, current_month = None, None

    try:
        current_year = _date_from_string(year=request.GET["year"],
                                         year_format="%Y")
    except (KeyError, Http404):
        pass

    if current_year:
        try:
            current_month = _date_from_string(
                year=current_year.year,
                year_format="%Y",
                month=request.GET["month"],
                month_format="%m",
            )
        except (KeyError, Http404):
            pass

    since, until = None, None

    if current_month:
        since = make_date_lookup_value(current_month)
        until = make_date_lookup_value(current_month +
                                       relativedelta.relativedelta(months=1))
    elif current_year:
        since = make_date_lookup_value(current_year)
        until = make_date_lookup_value(current_year +
                                       relativedelta.relativedelta(years=1))

    date_kwargs = ({
        "published__gte": since,
        "published__lt": until
    } if since and until else None)

    def _filter_queryset(qs, with_date_kwargs=True):
        qs = qs.published().exclude_blocked(request.user)
        if with_date_kwargs and date_kwargs:
            return qs.filter(**date_kwargs)
        return qs

    _, querysets = get_activity_querysets(lambda model: _filter_queryset(
        model.objects.for_activity_stream(request.user, request.community).
        distinct(),
        with_date_kwargs=False,
    ))

    querysets = [
        qs.only("pk",
                "published").select_related(None).dates("published", "month")
        for qs in querysets
    ]

    dates = sorted(set(itertools.chain.from_iterable(querysets)))

    sort_order = request.GET.get("order", "desc")

    params = request.GET.copy()
    params["order"] = "desc" if sort_order == "asc" else "asc"
    if "page" in params:
        params.pop("page")
    reverse_sort_url = f"{request.path}?{params.urlencode()}"

    selected_dates = dates

    if current_year:
        selected_dates = [
            date for date in dates if date.year == current_year.year
        ]

    if current_month:
        selected_dates = [
            date for date in selected_dates
            if date.month == current_month.month
        ]

    response = render_activity_stream(
        request,
        _filter_queryset,
        "activities/timeline.html",
        ordering="published" if sort_order == "asc" else "-published",
        page_size=settings.LONG_PAGE_SIZE,
        extra_context={
            "current_month": current_month.month if current_month else None,
            "current_year": current_year.year if current_year else None,
            "date_filters": date_kwargs,
            "dates": dates,
            "months": get_months(dates),
            "order": sort_order,
            "reverse_sort_url": reverse_sort_url,
            "selected_dates": selected_dates,
            "selected_months": get_months(selected_dates),
            "selected_years": get_years(selected_dates),
            "years": get_years(dates),
        },
    )

    for obj in response.context_data["object_list"]:
        obj["month"] = date_format(obj["published"], "F Y")
    return response
예제 #34
0
 def date(self):
     kwargs = self._get_kwargs_for_date_from_string()
     return _date_from_string(**kwargs)