Python django.utils.timezone.now() Examples

The following are 30 code examples of django.utils.timezone.now(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.timezone , or try the search function .
Example #1
Source File: serializers.py    From controller with MIT License 7 votes vote down vote up
def create(self, validated_data):
        now = timezone.now()
        user = User(
            email=validated_data.get('email'),
            username=validated_data.get('username'),
            last_login=now,
            date_joined=now,
            is_active=True
        )

        if validated_data.get('first_name'):
            user.first_name = validated_data['first_name']

        if validated_data.get('last_name'):
            user.last_name = validated_data['last_name']

        user.set_password(validated_data['password'])
        # Make the first signup an admin / superuser
        if not User.objects.filter(is_superuser=True).exists():
            user.is_superuser = user.is_staff = True

        user.save()
        return user 
Example #2
Source File: servo_tags.py    From Servo with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def relative_date(value):
    if value in ('', None):
        return ''

    current = timezone.now()
    
    if (current - value) > timedelta(days=1):
        return date(value, "SHORT_DATETIME_FORMAT")
        
    return naturaltime(value) 
Example #3
Source File: test_models.py    From cookiecutter-django-iot with MIT License 6 votes vote down vote up
def test_latest_by(self):
        # set up status going backward in time
        sample_time = timezone.now()
        for ihour in range(10):
            PowerStatus.objects.create(
                valid_at=sample_time-timedelta(hours=ihour),
                device=self.device,
                is_on=True,
            )

        # get latest and earliest
        latest = PowerStatus.objects.latest()
        earliest = PowerStatus.objects.earliest()

        # latest should have later valid_at but earlier created_at
        self.assertGreater(latest.valid_at, earliest.valid_at)
        self.assertLess(latest.created_at, earliest.created_at) 
Example #4
Source File: account.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def register(request):
    """
    New user applying for access
    """
    form = RegistrationForm()
    data = {'title': _("Register")}

    if request.method == 'POST':

        form = RegistrationForm(request.POST)

        if form.is_valid():
            user = User(is_active=False)
            user.email = form.cleaned_data['email']
            user.last_name = form.cleaned_data['last_name']
            user.first_name = form.cleaned_data['first_name']
            user.set_password(form.cleaned_data['password'])
            user.save()

            messages.success(request, _(u'Your registration is now pending approval.'))

            return redirect(login)

    data['form'] = form
    return render(request, 'accounts/register.html', data) 
Example #5
Source File: signing.py    From normandy with Mozilla Public License 2.0 6 votes vote down vote up
def check_validity(not_before, not_after, expire_early):
    """
    Check validity dates.

    If not_before is in the past, and not_after is in the future,
    return True, otherwise raise an Exception explaining the problem.

    If expire_early is passed, an exception will be raised if the
    not_after date is too soon in the future.
    """
    now = datetime.utcnow().replace(tzinfo=pytz.utc)
    if not_before > not_after:
        raise BadCertificate(f"not_before ({not_before}) after not_after ({not_after})")
    if now < not_before:
        raise CertificateNotYetValid(not_before)
    if now > not_after:
        raise CertificateExpired(not_after)
    if expire_early:
        if now + expire_early > not_after:
            raise CertificateExpiringSoon(expire_early)
    return True 
Example #6
Source File: senddigest.py    From open-synthesis with GNU General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        """Handle the command invocation."""
        if options['frequency'] == 'daily':
            self.report(send_digest_emails(DigestFrequency.daily))
        elif options['frequency'] == 'weekly':
            digest_day = getattr(settings, 'DIGEST_WEEKLY_DAY')
            current_day = timezone.now().weekday()
            if current_day == digest_day or options['force']:
                if current_day != digest_day and options['force']:
                    msg = 'Forcing weekly digest to be sent (scheduled=%s, current=%s)' % (digest_day, current_day)
                    self.stdout.write(self.style.WARNING(msg))  # pylint: disable=no-member
                self.report(send_digest_emails(DigestFrequency.weekly))
            else:
                msg = 'Skipping weekly digest until day %s (current=%s)' % (digest_day, current_day)
                self.stdout.write(self.style.WARNING(msg))  # pylint: disable=no-member
        else:
            raise CommandError('Expected frequency "daily" or "weekly"') 
Example #7
Source File: models.py    From django-healthchecks with MIT License 6 votes vote down vote up
def _update(cls, name, default_timeout=None, timeout=None):
        """Internal function to update a heartbeat.
        Use :func:`django_healthchecks.heartbeats.update_heartbeat` instead.
        """
        extra_updates = {}
        if timeout is not None:
            extra_updates['timeout'] = timeout

        rows = cls.objects.filter(name=name).update(last_beat=now(), **extra_updates)
        if not rows:
            return cls.objects.create(
                name=name,
                enabled=True,
                timeout=timeout or default_timeout or _get_default_timeout(),
                last_beat=now(),
            ) 
Example #8
Source File: order.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def close(self, user):
        """Close this service order."""
        if Configuration.autocomplete_repairs():
            for r in self.repair_set.active():
                try:
                    r.set_status_code('RFPU')
                    r.close(user)
                except Exception as e:
                    # notify the creator of the GSX repair instead of just erroring out
                    e = self.notify("gsx_error", e, user)
                    e.notify_users.add(r.created_by)

        if self.queue and self.queue.status_closed:
            self.set_status(self.queue.status_closed, user)

        self.notify("close_order", _(u"Order %s closed") % self.code, user)
        self.closed_by = user
        self.closed_at = timezone.now()
        self.state = self.STATE_CLOSED
        self.save() 
Example #9
Source File: escalations.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def submit(self):
        esc = self.to_gsx()
        esc.shipTo = self.gsx_account.ship_to
        esc.issueTypeCode = self.issue_type

        if len(self.contexts) > 2:
            ec = []
            for k, v in json.loads(self.contexts).items():
                ec.append(Context(k, v))

            esc.escalationContext = ec

        result = esc.create()
        self.submitted_at = timezone.now()
        self.escalation_id = result.escalationId

        self.save() 
Example #10
Source File: models.py    From djng with MIT License 6 votes vote down vote up
def _create_user(self, email, password,
                     is_staff, is_superuser, **extra_fields):
        """
        Creates and saves a User with the given username, email and password.
        """
        now = timezone.now()
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email,
                          is_staff=is_staff, is_active=True,
                          is_superuser=is_superuser,
                          date_joined=now, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user 
Example #11
Source File: views.py    From django-accounting with MIT License 6 votes vote down vote up
def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        orga = organization_manager.get_selected_organization(self.request)

        # currrent quarter
        now = timezone.now()
        start = date(
            year=now.year,
            month=(now.month - ((now.month - 1) % 3)),
            day=1
        )
        end = start + relativedelta(months=3)

        report = ProfitAndLossReport(orga, start=start, end=end)
        report.generate()
        ctx['summaries'] = report.summaries
        ctx['total_summary'] = report.total_summary
        return ctx 
Example #12
Source File: views.py    From django-accounting with MIT License 6 votes vote down vote up
def get_initial(self):
        initial = super().get_initial()

        # currrent quarter
        now = timezone.now()
        start = date(
            year=now.year,
            month=(now.month - ((now.month - 1) % 3)),
            day=1
        )
        end = start + relativedelta(months=3)

        initial['date_from'] = start
        initial['date_to'] = end

        return initial 
Example #13
Source File: models.py    From django-accounting with MIT License 6 votes vote down vote up
def check_date_dued(self, check):
        if self.date_dued is None:
            check.mark_fail(message="No due date specified")
            return check

        if self.total_excl_tax == D('0'):
            check.mark_fail(message="The invoice has no value")
            return check

        if self.is_fully_paid():
            last_payment = self.payments.all().first()
            formatted_date = last_payment.date_paid.strftime('%B %d, %Y')
            check.mark_pass(message="Has been paid on the {}"
                .format(formatted_date))
            return check

        if timezone.now().date() > self.date_dued:
            check.mark_fail(message="The due date has been exceeded.")
        else:
            check.mark_pass()
        return check 
Example #14
Source File: format_filters.py    From django-accounting with MIT License 6 votes vote down vote up
def smartdate(value):
    if isinstance(value, datetime.datetime):
        now = django_now()
    else:
        now = datetime.date.today()

    timedelta = value - now
    format = _(u"%(delta)s %(unit)s")
    delta = abs(timedelta.days)

    if delta > 30:
        delta = int(delta / 30)
        unit = _(u"mois")
    else:
        unit = _(u"jours")

    ctx = {
        'delta': delta,
        'unit': unit,
    }

    return format % ctx 
Example #15
Source File: cleanup.py    From polls-api with MIT License 6 votes vote down vote up
def handle(self, *args, **kwargs):
        with open('polls/fixtures/initial_data.json') as fp:
            initial_data = json.load(fp)

        initial_questions = filter(lambda m: m['model'] == 'polls.question', initial_data)
        initial_question_pks = map(lambda m: m['pk'], initial_questions)
        one_hour_ago = timezone.now() - timedelta(hours=1)
        qs = Question.objects.exclude(id__in=initial_question_pks).filter(published_at__lt=one_hour_ago)

        print('Deleting {} questions'.format(qs.count()))
        qs.delete()

        qa = Vote.objects.all()

        print('Deleting {} votes'.format(qs.count()))
        qs.delete() 
Example #16
Source File: test_models.py    From cookiecutter-django-iot with MIT License 6 votes vote down vote up
def test_latest_by(self):
        # set up observations going backward in time
        sample_time = timezone.now()
        for ihour in range(10):
            Attribute.objects.create(
                valid_at=sample_time-timedelta(hours=ihour),
                value=ihour*0.5,
                units='kW',
                device=self.device,
            )

        # get latest and earliest
        latest = Attribute.objects.latest()
        earliest = Attribute.objects.earliest()

        # latest should have later valid_at but earlier created_at
        self.assertGreater(latest.valid_at, earliest.valid_at)
        self.assertLess(latest.created_at, earliest.created_at) 
Example #17
Source File: models.py    From normandy with Mozilla Public License 2.0 5 votes vote down vote up
def save(self, *args, **kwargs):
        self.action.validate_arguments(self.arguments, self)

        if not self.created:
            self.created = timezone.now()
        self.updated = timezone.now()
        super().save(*args, **kwargs) 
Example #18
Source File: update_action_signatures.py    From normandy with Mozilla Public License 2.0 5 votes vote down vote up
def get_outdated_actions(self):
        outdated_age = timedelta(seconds=settings.AUTOGRAPH_SIGNATURE_MAX_AGE)
        outdated_filter = Q(signature__timestamp__lt=timezone.now() - outdated_age)
        missing_filter = Q(signature=None)
        return Action.objects.filter(outdated_filter | missing_filter) 
Example #19
Source File: test_donation.py    From donation-tracker with Apache License 2.0 5 votes vote down vote up
def test_anonymous(self):
        # Anonymous donation is anonymous
        donation = models.Donation(
            timereceived=timezone.now(),
            amount=Decimal(1.5),
            domain='PAYPAL',
            requestedvisibility='ANON',
            event=self.event,
        )
        self.assertTrue(donation.anonymous())

        # Donation from an anonymous donor with CURR is anonymous
        donation = models.Donation(
            timereceived=timezone.now(),
            amount=Decimal(1.5),
            domain='PAYPAL',
            requestedvisibility='CURR',
            donor=models.Donor(visibility='ANON'),
            event=self.event,
        )
        self.assertTrue(donation.anonymous())

        # Donation from a non-anonymous donor with CURR is not anonymous
        donation = models.Donation(
            timereceived=timezone.now(),
            amount=Decimal(1.5),
            domain='PAYPAL',
            requestedvisibility='CURR',
            donor=models.Donor(visibility='ALIAS'),
            event=self.event,
        )
        self.assertFalse(donation.anonymous()) 
Example #20
Source File: models.py    From django-healthchecks with MIT License 5 votes vote down vote up
def expired(self):
        """Tell which services no longer appear to send heartbeats."""
        return self.annotate_expires_at().filter(expires_at__lt=now()) 
Example #21
Source File: base.py    From django-phone-verify with GNU General Public License v3.0 5 votes vote down vote up
def check_security_code_expiry(cls, stored_verification):
        """
        Returns True if the `security_code` for the `stored_verification` is expired.
        """
        time_difference = timezone.now() - stored_verification.created_at
        if time_difference.seconds > django_settings.PHONE_VERIFICATION.get(
            "SECURITY_CODE_EXPIRATION_TIME"
        ):
            return True
        return False 
Example #22
Source File: boards.py    From open-synthesis with GNU General Public License v3.0 5 votes vote down vote up
def create_board(request):
    """Return a board creation view, or handle the form submission.

    Set default permissions for the new board. Mark board creator as a board follower.
    """
    if request.method == 'POST':
        form = BoardCreateForm(request.POST)
        if form.is_valid():
            with transaction.atomic():
                board = form.save(commit=False)
                board.creator = request.user
                board.pub_date = timezone.now()
                board.save()
                for hypothesis_key in ['hypothesis1', 'hypothesis2']:
                    Hypothesis.objects.create(
                        board=board,
                        hypothesis_text=form.cleaned_data[hypothesis_key],
                        creator=request.user,
                    )
                BoardFollower.objects.update_or_create(board=board, user=request.user, defaults={
                    'is_creator': True,
                })

            return HttpResponseRedirect(reverse('openach:detail', args=(board.id,)))
    else:
        form = BoardCreateForm()
    return render(request, 'boards/create_board.html', {'form': form}) 
Example #23
Source File: instanceworkflowobject.py    From django-river with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def approve(self, as_user, next_state=None):
        available_approvals = self.get_available_approvals(as_user=as_user)
        number_of_available_approvals = available_approvals.count()
        if number_of_available_approvals == 0:
            raise RiverException(ErrorCode.NO_AVAILABLE_NEXT_STATE_FOR_USER, "There is no available approval for the user.")
        elif next_state:
            available_approvals = available_approvals.filter(transition__destination_state=next_state)
            if available_approvals.count() == 0:
                available_states = self.get_available_states(as_user)
                raise RiverException(ErrorCode.INVALID_NEXT_STATE_FOR_USER, "Invalid state is given(%s). Valid states is(are) %s" % (
                    next_state.__str__(), ','.join([ast.__str__() for ast in available_states])))
        elif number_of_available_approvals > 1 and not next_state:
            raise RiverException(ErrorCode.NEXT_STATE_IS_REQUIRED, "State must be given when there are multiple states for destination")

        approval = available_approvals.first()
        approval.status = APPROVED
        approval.transactioner = as_user
        approval.transaction_date = timezone.now()
        approval.previous = self.recent_approval
        approval.save()

        if next_state:
            self.cancel_impossible_future(approval)

        has_transit = False
        if approval.peers.filter(status=PENDING).count() == 0:
            approval.transition.status = DONE
            approval.transition.save()
            previous_state = self.get_state()
            self.set_state(approval.transition.destination_state)
            has_transit = True
            if self._check_if_it_cycled(approval.transition):
                self._re_create_cycled_path(approval.transition)
            LOGGER.debug("Workflow object %s is proceeded for next transition. Transition: %s -> %s" % (
                self.workflow_object, previous_state, self.get_state()))

        with self._approve_signal(approval), self._transition_signal(has_transit, approval), self._on_complete_signal():
            self.workflow_object.save() 
Example #24
Source File: site.py    From open-synthesis with GNU General Public License v3.0 5 votes vote down vote up
def index(request):
    """Return a homepage view showing project information, news, and recent boards."""
    # Show all of the boards until we can implement tagging, search, etc.
    latest_board_list = Board.objects.user_readable(request.user)[:5]
    latest_project_news = ProjectNews.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]
    context = {
        'latest_board_list': latest_board_list,
        'latest_project_news': latest_project_news,
    }
    return render(request, 'boards/index.html', context) 
Example #25
Source File: test_views.py    From django-oauth-toolkit-jwt with MIT License 5 votes vote down vote up
def test_refresh_token(self):
        access_token = AccessToken.objects.create(
            user=self.test_user, token="1234567890",
            application=self.application,
            expires=timezone.now() + datetime.timedelta(days=1),
            scope="read write"
        )
        refresh_token = RefreshToken.objects.create(
            access_token=access_token,
            user=self.test_user,
            application=self.application
        )

        request_data = {
            "grant_type": "refresh_token",
            "refresh_token": refresh_token.token,
        }
        auth_headers = get_basic_auth_header(self.application.client_id,
                                             self.application.client_secret)
        response = self.client.post(
            reverse("oauth2_provider_jwt:token"), data=request_data,
            **auth_headers)
        self.assertEqual(response.status_code, 200)
        content = json.loads(response.content.decode("utf-8"))
        self.assertIn(type(content["access_token_jwt"]).__name__,
                      ('unicode', 'str')) 
Example #26
Source File: models.py    From open-synthesis with GNU General Public License v3.0 5 votes vote down vote up
def was_published_recently(self):
        """Return True iff the Board was created recently."""
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now 
Example #27
Source File: tasks.py    From cookiecutter-django-iot with MIT License 5 votes vote down vote up
def set_status(device_id=None, is_on=True, **kwargs):
    """
    Sets the device status using the device vendor's API,
    stores the new status in the database,
    and returns the pks of the status.
    """
    # SAMPLE IMPLEMENTATION
    # check device exists
    # device = Device.objects.get(pk=device_id)

    # # turn on or off
    # if is_on:
    #     result = client.turn_on(device_id)
    # else:
    #     result = client.turn_off(device_id)

    # # create status
    # if result['status'] == 'ok':
    #     status = device.powerstatus_set.create(
    #         valid_at=timezone.now(),
    #         is_on=is_on,
    #     )

    #     # return pk
    #     return [status.pk]
    # else:
    #     return []
    raise NotImplementedError 
Example #28
Source File: tasks.py    From cookiecutter-django-iot with MIT License 5 votes vote down vote up
def pull_status(device_id=None, **kwargs):
    """
    Pulls the current device status from the device vendor's API,
    stores the status in the database,
    and returns the pks of the status.
    """
    # SAMPLE IMPLEMENTATION
    # # check device exists
    # device = Device.objects.get(pk=device_id)

    # # fetch status
    # status_message = client.get_status(device_id)

    # # create status
    # if status_message == 'on':
    #     is_on = True
    # else:
    #     is_on = False
    # status = device.powerstatus_set.create(
    #     valid_at=timezone.now(),
    #     is_on=is_on,
    # )

    # # return pk
    # return [status.pk]
    raise NotImplementedError 
Example #29
Source File: test_models.py    From cookiecutter-django-iot with MIT License 5 votes vote down vote up
def test_value_numeric(self):
        # raises ValueError when trying to cast string 'badvalue' to float
        self.assertRaises(ValueError, Attribute.objects.create,
                          valid_at=timezone.now(),
                          device=self.device,
                          value='badvalue',
                          units='goodunits') 
Example #30
Source File: user_manager.py    From raveberry with GNU Lesser General Public License v3.0 5 votes vote down vote up
def update_user_count(self) -> None:
        """Go through all recent requests and delete those that were too long ago."""
        now = timezone.now()
        for key, value in list(UserManager.last_requests.items()):
            if (now - value).seconds >= self.inactivity_period:
                del UserManager.last_requests[key]
        self.last_user_count_update = now