django.utils.timezone.now.date

Here are the examples of the python api django.utils.timezone.now.date taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

155 Examples 7

Example 1

Project: site Source File: contests.py
Function: get
    def get(self, request, *args, **kwargs):
        try:
            self.year = int(kwargs['year'])
            self.month = int(kwargs['month'])
        except (KeyError, ValueError):
            raise ImproperlyConfigured(_('ContestCalender requires integer year and month'))
        self.today = timezone.now().date()
        return self.render()

Example 2

Project: onlineweb4 Source File: models.py
Function: check_marks
    def _check_marks(self, response, user):
        expiry_date = get_expiration_date(user)
        if expiry_date and expiry_date > timezone.now().date():
            # Offset is currently 1 day if you have marks, regardless of amount.
            mark_offset = timedelta(days=1)
            postponed_registration_start = self.registration_start + mark_offset

            before_expiry = self.registration_start.date() < expiry_date

            if postponed_registration_start > timezone.now() and before_expiry:
                if 'offset' in response and response['offset'] < postponed_registration_start \
                        or 'offset' not in response:
                    response['status'] = False
                    response['status_code'] = 401
                    response['message'] = _("Din påmelding er utsatt grunnet prikker.")
                    response['offset'] = postponed_registration_start
        return response

Example 3

Project: portal Source File: test_forms.py
    def test_edit_meetup_form(self):
        """Test edit meetup"""
        incomplete_data = {'slug': 'slug', 'date': timezone.now().date()}
        form = EditMeetupForm(data=incomplete_data)
        self.assertFalse(form.is_valid())

        date = (timezone.now() + timedelta(2)).date()
        time = timezone.now().time()

        data = {'slug': 'foobar', 'title': 'Foo Bar', 'date': date, 'time': time,
                'description': "It's a test meetup.", 'venue': 'test address'}
        form = EditMeetupForm(instance=self.meetup, data=data)
        self.assertTrue(form.is_valid())
        form.save()
        meetup = Meetup.objects.get()
        self.assertEqual(meetup.title, 'Foo Bar')
        self.assertEqual(meetup.slug, 'foobar')
        self.assertEqual(meetup.created_by, self.systers_user)
        self.assertEqual(meetup.meetup_location, self.meetup_location)

Example 4

Project: django-encrypted-fields Source File: tests.py
    def test_date_field_encrypted(self):
        plaindate = timezone.now().date()

        model = TestModel()
        model.date = plaindate
        model.save()

        ciphertext = self.get_db_value('date', model.id)
        fresh_model = TestModel.objects.get(id=model.id)

        self.assertNotEqual(ciphertext, plaindate.isoformat())
        self.assertEqual(fresh_model.date, plaindate)

Example 5

Project: portal Source File: test_views.py
Function: set_up
    def setUp(self):
        super(DeleteMeetupViewTestCase, self).setUp()
        self.meetup2 = Meetup.objects.create(title='Fooba', slug='fooba',
                                             date=timezone.now().date(),
                                             time=timezone.now().time(),
                                             description='This is test Meetup',
                                             meetup_location=self.meetup_location,
                                             created_by=self.systers_user,
                                             last_updated=timezone.now())
        self.client = Client()

Example 6

Project: portal Source File: forms.py
Function: clean_time
    def clean_time(self):
        time = self.cleaned_data.get('time')
        date = self.cleaned_data.get('date')
        if time:
            if date == timezone.now().date() and time < timezone.now().time():
                raise forms.ValidationError("Time should not be a time that has already passed.")
        return time

Example 7

Project: onlineweb4 Source File: views.py
Function: get_expiry_date
def get_expiry_date(started_year, length_of_fos):
    today = timezone.now().date()
    # Expiry dates should be 15th September, so that we have time to get new lists from NTNU
    new_expiry_date = datetime.date(
        started_year, 9, 16) + datetime.timedelta(days=365*length_of_fos)
    # Expiry dates in the past sets the expiry date to next september
    if new_expiry_date < today:
        if today < datetime.date(today.year, 9, 15):
            new_expiry_date = datetime.date(today.year, 9, 15)
        else:
            new_expiry_date = datetime.date(
                today.year, 9, 16) + datetime.timedelta(days=365)
    return new_expiry_date

Example 8

Project: pythondigest Source File: test_views.py
    def test_context_var_issue_if_has_active_issues_with_filled_published_at_field(
        self):
        date = timezone.now().date()
        issue = Issue.objects.create(title='Title 1',
                                     status='active',
                                     published_at=date)

        request = self.factory.get(self.url)
        response = IndexView.as_view()(request)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context_data['issue'], issue)

Example 9

Project: onlineweb4 Source File: models.py
Function: save
    def save(self, *args, **kwargs):
        run_history_update = False
        if not self.expiration_date:
            self.expiration_date = timezone.now().date()
            run_history_update = True
        super(MarkUser, self).save(*args, **kwargs)
        if run_history_update:
            _fix_mark_history(self.user)

Example 10

Project: coursys Source File: models.py
Function: timezone_today
def timezone_today():
    """
    Return the timezone-aware version of datetime.date.today()

    :return: Today's date corrected for timezones
    """
    return timezone.now().date()

Example 11

Project: datal Source File: primitives.py
def previous_month_year():
    today = now().date()

    month = today.month

    if month != 1:
        return today.year

    return today.year - 1

Example 12

Project: wagtail Source File: models.py
Function: garbage_collect
    @classmethod
    def garbage_collect(cls, days=None):
        """
        Deletes all QueryDailyHits records that are older than a set number of days
        """
        days = getattr(settings, 'WAGTAILSEARCH_HITS_MAX_AGE', 7) if days is None else days
        min_date = timezone.now().date() - datetime.timedelta(days)

        cls.objects.filter(date__lt=min_date).delete()

Example 13

Project: froide Source File: forms.py
    def clean_date(self):
        date = self.cleaned_data['date']
        now = timezone.now().date()
        if date > now:
            raise forms.ValidationError(_("Your reply date is in the future, that is not possible."))
        return date

Example 14

Project: silk Source File: silk_filters.py
def _silk_date_time(dt):
    today = timezone.now().date()
    if dt.date() == today:
        dt_strftime = dt.strftime('%H:%M:%S.%f')
        return _process_microseconds(dt_strftime)
    else:
        return _process_microseconds(dt.strftime('%Y.%m.%d %H:%M.%f'))

Example 15

Project: pythondigest Source File: test_views.py
    def test_context_var_items_if_has_no_related_active_items(self):
        past = timezone.now().date() - timezone.timedelta(days=1)

        issue = Issue.objects.create(title='Title 1',
                                     status='active',
                                     published_at=past)
        Item.objects.create(title='Item 1 title', link='[email protected]',
                            issue=issue, status='active')

        Issue.objects.create(title='Title 2', status='active',
                             published_at=timezone.now().date())

        request = self.factory.get(self.url)
        response = IndexView.as_view()(request)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(list(response.context_data['items']), [])

Example 16

Project: onlineweb4 Source File: tests.py
    def testIsMembershipApplication(self):
        self.logger.debug("Testing method to see if application is for membership")
        self.approval.field_of_study = 1
        self.assertEqual(self.approval.is_membership_application(), False)
        self.approval.started_date = timezone.now().date()
        self.assertEqual(self.approval.is_membership_application(), False)
        self.approval.new_expiry_date = timezone.now().date()
        self.assertEqual(self.approval.is_membership_application(), True)
        self.approval.field_of_study = 0
        self.assertEqual(self.approval.is_membership_application(), True)
        self.approval.started_date = None
        self.assertEqual(self.approval.is_membership_application(), True)
        self.approval.new_expiry_date = None
        self.assertEqual(self.approval.is_membership_application(), False)

Example 17

Project: portal Source File: test_forms.py
    def test_add_meetup_form(self):
        """Test add Meetup form"""
        invalid_data = {'title': 'abc', 'date': timezone.now().date()}
        form = AddMeetupForm(data=invalid_data, created_by=self.systers_user,
                             meetup_location=self.meetup_location)
        self.assertFalse(form.is_valid())

        date = (timezone.now() + timedelta(2)).date()
        time = timezone.now().time()
        data = {'title': 'Foo', 'slug': 'foo', 'date': date, 'time': time,
                'description': "It's a test meetup."}
        form = AddMeetupForm(data=data, created_by=self.systers_user,
                             meetup_location=self.meetup_location)
        self.assertTrue(form.is_valid())
        form.save()
        new_meetup = Meetup.objects.get(slug='foo')
        self.assertTrue(new_meetup.title, 'Foo')
        self.assertTrue(new_meetup.created_by, self.systers_user)
        self.assertTrue(new_meetup.meetup_location, self.meetup_location)

Example 18

Project: onlineweb4 Source File: views.py
Function: past
@login_required
@permission_required('events.view_event', return_403=True)
def past(request):
    if not has_access(request):
        raise PermissionDenied

    allowed_events = get_group_restricted_events(request.user, True)
    events = allowed_events.filter(event_start__lt=timezone.now().date()).order_by('-event_start')

    context = get_base_context(request)
    context['events'] = events

    return render(request, 'events/dashboard/index.html', context)

Example 19

Project: silver Source File: base.py
Function: cancel
    def _cancel(self, cancel_date=None):
        if cancel_date:
            self.cancel_date = datetime.strptime(cancel_date, '%Y-%m-%d').date()
        if not self.cancel_date and not cancel_date:
            self.cancel_date = timezone.now().date()

        self._save_pdf(state=self.STATES.CANCELED)

Example 20

Project: onlineweb4 Source File: tests.py
Function: test_warning
    def test_warning(self):
        feedback_relation = self.create_feedback_relation(deadline=timezone.now().date() + timedelta(days=2))
        message = FeedbackMail.generate_message(feedback_relation, self.logger)

        self.assertEqual(message.status, "Warning message")
        self.assertTrue(message.send)

Example 21

Project: portal Source File: test_models.py
Function: set_up
    def setUp(self):
        super(RsvpTestCase, self).setUp()
        self.meetup = Meetup.objects.create(title="Test Meetup", slug="baz",
                                            date=timezone.now().date(), time=timezone.now().time(),
                                            venue="FooBar colony",
                                            description="This is a testing meetup.",
                                            meetup_location=self.meetup_location,
                                            created_by=self.systers_user)
        self.rsvp = Rsvp.objects.create(user=self.systers_user, meetup=self.meetup)

Example 22

Project: portal Source File: test_views.py
Function: set_up
    def setUp(self):
        self.user = User.objects.create_user(username='foo', password='foobar')
        self.systers_user = SystersUser.objects.get()
        country = Country.objects.create(name='Bar', continent='AS')
        self.location = City.objects.create(name='Baz', display_name='Baz', country=country)
        self.meetup_location = MeetupLocation.objects.create(
            name="Foo Systers", slug="foo", location=self.location,
            description="It's a test meetup location", sponsors="BarBaz")

        self.meetup = Meetup.objects.create(title='Foo Bar Baz', slug='foo-bar-baz',
                                            date=timezone.now().date(),
                                            time=timezone.now().time(),
                                            description='This is test Meetup',
                                            meetup_location=self.meetup_location,
                                            created_by=self.systers_user,
                                            last_updated=timezone.now())

Example 23

Project: silver Source File: base.py
    @property
    def fields_for_payment_creation(self):
        fields = {
            'customer': self.customer,
            'provider': self.provider,
            'due_date': self.due_date,
            'amount': self.total,
            'currency': self.currency,
            'visible': (self.state in [BillingDocuement.STATES.ISSUED,
                                       BillingDocuement.STATES.PAID]),
            'currency_rate_date': timezone.now().date(),
            'status': (Payment.Status.Unpaid if self.total else
                       Payment.Status.Paid),
        }

        return fields

Example 24

Project: wagtail Source File: models.py
    def add_hit(self, date=None):
        if date is None:
            date = timezone.now().date()
        daily_hits, created = QueryDailyHits.objects.get_or_create(query=self, date=date)
        daily_hits.hits = models.F('hits') + 1
        daily_hits.save()

Example 25

Project: coursys Source File: models.py
Function: timezone_today
def timezone_today():
    """
    Return the timezone-aware version of datetime.date.today()
    """
    # field default must be a callable (so it's the "today" of the request, not the "today" of the server startup)
    return timezone.now().date()

Example 26

Project: datal Source File: primitives.py
def previous_month():
    today = now().date()

    month = today.month

    if month != 1:
        return month - 1

    return 12

Example 27

Project: movide Source File: models.py
Function: count_by_day
    def count_by_day(self, objects):
        """
        Count messages sent by day.
        """
        if len(objects) == 0:
            return []
        end = now().date()
        return self.calculate_days(objects, self.first_message_time(), end)

Example 28

Project: djangorestframework-timed-auth-token Source File: test_models.py
def test_calculate_new_expiration_can_be_overridden_on_model(token, settings):
    settings.TIMED_AUTH_TOKEN = {'DEFAULT_VALIDITY_DURATION': timedelta(days=5)}
    CustomUser.token_validity_duration = timedelta(days=10)
    token.calculate_new_expiration()
    expected = timezone.now().date() + timedelta(days=10)
    actual = token.expires.date()
    assert expected == actual

Example 29

Project: datal Source File: primitives.py
Function: today
def today(days=0, fmt="%d/%m/%Y"):
    today = now().date()

    if days != 0:
        today = today + timedelta(days=days)

    return today.strftime(fmt)

Example 30

Project: pythondigest Source File: test_views.py
    def test_context_var_items_if_has_related_not_active_items(self):
        date = timezone.now().date()
        issue = Issue.objects.create(title='Title 1',
                                     status='active',
                                     published_at=date)

        section = Section.objects.create(title='Section 1 title', priority=1)

        Item.objects.create(title='Item 1 title', link='[email protected]',
                            section=section, issue=issue, status='pending')

        request = self.factory.get(self.url)
        response = IndexView.as_view()(request)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(list(response.context_data['items']), [])

Example 31

Project: django-bmf Source File: models.py
    def due_days(self):
        if self.due_date:
            time = now().date()
            if time >= self.due_date:
                return 0
            return (self.due_date - time).days

Example 32

Project: seriesly Source File: tasks.py
@app.task
def email_task(request):
    filter_date = timezone.now().date() + timedelta(days=1)
    subscriptions = Subscription.objects.filter(activated_mail=True,
                                                next_airtime__lte=filter_date)
    counter = 0
    for sub in subscriptions:
        Subscription.add_email_task(sub.pk)
        counter += 1
    return counter

Example 33

Project: djangogirls Source File: test_models.py
    def setUp(self):
        """Setting up models with mommy."""
        self.future_date = timezone.now().date() + timedelta(days=45)
        self.meetup_not_ready = mommy.make(Meetup, review_status=Meetup.OPEN)
        self.meetup_ready_no_exp_date = mommy.make(
            Meetup,
            review_status=Meetup.READY_TO_PUBLISH,
            expiration_date=None
        )
        self.meetup_ready_future_exp_date = mommy.make(
            Meetup,
            review_status=Meetup.READY_TO_PUBLISH,
            expiration_date=self.future_date
        )

Example 34

Project: silver Source File: base.py
Function: pay
    def _pay(self, paid_date=None):
        if paid_date:
            self.paid_date = datetime.strptime(paid_date, '%Y-%m-%d').date()
        if not self.paid_date and not paid_date:
            self.paid_date = timezone.now().date()

        self._save_pdf(state=self.STATES.PAID)

Example 35

Project: onlineweb4 Source File: tests.py
Function: test_unicode_method
    def testUnicodeMethod(self):
        self.logger.debug("Testing unicode output for approval")
        self.assertEqual(self.approval.__str__(), "Tom søknad for Søker Søkersen")

        self.approval.new_expiry_date = timezone.now().date()
        self.assertEqual(self.approval.__str__(), "Medlemskapssøknad for Søker Søkersen")

        self.approval.field_of_study = 1
        self.approval.started_date = timezone.now().date()
        self.assertEqual(self.approval.__str__(), "Medlemskaps- og studieretningssøknad for Søker Søkersen")

        self.approval.new_expiry_date = None
        self.assertEqual(self.approval.__str__(), "studieretningssøknad for Søker Søkersen")

Example 36

Project: portal Source File: test_forms.py
Function: set_up
    def setUp(self):
        User.objects.create_user(username='foo', password='foobar')
        self.systers_user = SystersUser.objects.get()
        country = Country.objects.create(name='Bar', continent='AS')
        self.location = City.objects.create(name='Baz', display_name='Baz', country=country)
        self.meetup_location = MeetupLocation.objects.create(
            name="Foo Systers", slug="foo", location=self.location,
            description="It's a test meetup location", sponsors="BarBaz")

        self.meetup = Meetup.objects.create(title='Foo Bar Baz', slug='foobarbaz',
                                            date=timezone.now().date(),
                                            time=timezone.now().time(),
                                            description='This is test Meetup',
                                            meetup_location=self.meetup_location,
                                            created_by=self.systers_user,
                                            last_updated=timezone.now())

Example 37

Project: onlineweb4 Source File: tests.py
    def testIsFOSApplication(self):
        self.logger.debug("Testing method to see if application is for field of study update")
        self.approval.field_of_study = 1
        self.assertEqual(self.approval.is_fos_application(), False)
        self.approval.started_date = timezone.now().date()
        self.assertEqual(self.approval.is_fos_application(), True)
        self.approval.new_expiry_date = timezone.now().date()
        self.assertEqual(self.approval.is_fos_application(), True)
        self.approval.field_of_study = 0
        self.assertEqual(self.approval.is_fos_application(), False)
        self.approval.started_date = None
        self.assertEqual(self.approval.is_fos_application(), False)
        self.approval.new_expiry_date = None
        self.assertEqual(self.approval.is_fos_application(), False)

Example 38

Project: pythondigest Source File: test_views.py
    def test_context_var_items_if_has_related_active_items(self):
        date = timezone.now().date()
        issue = Issue.objects.create(title='Title 1',
                                     status='active',
                                     published_at=date)

        section = Section.objects.create(title='Section 1 title', priority=1)

        item = Item.objects.create(title='Item 1 title', link='[email protected]',

                                   section=section, issue=issue,
                                   status='active')

        request = self.factory.get(self.url)
        response = IndexView.as_view()(request)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(list(response.context_data['items']), [item])

Example 39

Project: onlineweb4 Source File: views.py
Function: index
@login_required
@permission_required('events.view_event', return_403=True)
def index(request):
    if not has_access(request):
        raise PermissionDenied

    allowed_events = get_group_restricted_events(request.user, True)
    events = allowed_events.filter(event_start__gte=timezone.now().date()).order_by('event_start')

    context = get_base_context(request)
    context['events'] = events

    return render(request, 'events/dashboard/index.html', context)

Example 40

Project: portal Source File: test_forms.py
    def test_add_meetup_form_with_passed_time(self):
        """Test add Meetup form with a time that has passed."""
        date = timezone.now().date()
        time = (timezone.now() - timedelta(2)).time()
        data = {'title': 'Foo', 'slug': 'foo', 'date': date, 'time': time,
                'description': "It's a test meetup."}
        form = AddMeetupForm(data=data, created_by=self.systers_user,
                             meetup_location=self.meetup_location)
        self.assertFalse(form.is_valid())
        self.assertTrue(form.errors['time'],
                        ["Time should not be a time that has already passed."])

Example 41

Project: onlineweb4 Source File: models.py
    def is_suspended(self, user):
        for suspension in user.get_active_suspensions():
            if not suspension.expiration_date or suspension.expiration_date > timezone.now().date():
                return True

        return False

Example 42

Project: silver Source File: documents_generator.py
Function: generate_all
    def _generate_all(self, billing_date=None, customers=None,
                      force_generate=False):
        """
        Generates the invoices/proformas for all the subscriptions that should
        be billed.
        """

        billing_date = billing_date or timezone.now().date()
        # billing_date -> the date when the billing docuements are issued.

        for customer in customers:
            if customer.consolidated_billing:
                self._generate_for_user_with_consolidated_billing(
                    customer, billing_date, force_generate
                )
            else:
                self._generate_for_user_without_consolidated_billing(
                    customer, billing_date, force_generate
                )

Example 43

Project: onlineweb4 Source File: tests.py
    def test_last_warning(self):
        feedback_relation = self.create_feedback_relation(deadline=timezone.now().date())
        message = FeedbackMail.generate_message(feedback_relation, self.logger)

        self.assertEqual(message.status, "Last warning")
        self.assertTrue(message.send)

Example 44

Project: portal Source File: test_models.py
Function: set_up
    def setUp(self):
        super(MeetupTestCase, self).setUp()
        self.meetup = Meetup.objects.create(title="Test Meetup", slug="baz",
                                            date=timezone.now().date(), time=timezone.now().time(),
                                            venue="FooBar colony",
                                            description="This is a testing meetup.",
                                            meetup_location=self.meetup_location,
                                            created_by=self.systers_user)

Example 45

Project: django-shop Source File: order.py
    def get_or_assign_number(self):
        """
        Set a unique number to identify this Order object. The first 4 digits represent the
        current year. The last five digits represent a zero-padded incremental counter.
        """
        if self.number is None:
            epoch = timezone.now().date()
            epoch = epoch.replace(epoch.year, 1, 1)
            aggr = Order.objects.filter(number__isnull=False, created_at__gt=epoch).aggregate(models.Max('number'))
            try:
                epoc_number = int(str(aggr['number__max'])[4:]) + 1
                self.number = int('{0}{1:05d}'.format(epoch.year, epoc_number))
            except (KeyError, ValueError):
                # the first order this year
                self.number = int('{0}00001'.format(epoch.year))
        return self.get_number()

Example 46

Project: pinax-calendars Source File: mixins.py
Function: dispatch
    def dispatch(self, request, *args, **kwargs):
        self.month = self.kwargs.get(self.month_kwarg_name)
        self.year = self.kwargs.get(self.year_kwarg_name)
        if self.month and self.year:
            self.date = datetime.date(
                year=int(self.year),
                month=int(self.month),
                day=1
            )
        else:
            self.date = timezone.now().date()
        return super(MonthlyMixin, self).dispatch(request, *args, **kwargs)

Example 47

Project: silver Source File: tweak_billing_log.py
Function: handle
    def handle(self, *args, **options):
        if options['date']:
            date = datetime.strptime(options['date'], '%Y-%m-%d')
        else:
            now = timezone.now().date()
            date = dt.date(now.year, now.month - 1, 1)

        for subscription in Subscription.objects.all():
            self.stdout.write('Tweaking for subscription %d' % subscription.id)
            BillingLog.objects.create(subscription=subscription,
                                      billing_date=date)

Example 48

Project: pythondigest Source File: dashboards.py
Function: labels
    def labels(self):
        # По оси `x` дни
        today = timezone.now().date()
        labels = [(today - datetime.timedelta(days=x)).strftime('%d.%m')
                  for x in range(self.limit_to)]
        return labels

Example 49

Project: djangorestframework-timed-auth-token Source File: test_models.py
def test_calculate_new_expiration_duration_can_be_set_in_settings(token, settings):
    settings.TIMED_AUTH_TOKEN = {'DEFAULT_VALIDITY_DURATION': timedelta(days=5)}
    token.calculate_new_expiration()
    expected = timezone.now().date() + timedelta(days=5)
    actual = token.expires.date()
    assert expected == actual

Example 50

Project: django-admin-cli Source File: tests.py
    def test_date(self):
        date = now().date()
        field = ['field='+strftime(date, se.SHORT_DATE_FORMAT)]
        call_command('cli', 'datemodel', 'add', field=field, stdout=self.stdout)
        self.assertEqual(1, models.DateModel.objects.count())
        self.assertEqual(date, models.DateModel.objects.get().field)
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4