Python django.utils.timezone.now() Examples

The following are 30 code examples for showing how to use django.utils.timezone.now(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.utils.timezone , or try the search function .

Example 1
Project: Servo   Author: fpsw   File: account.py    License: 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 2
Project: Servo   Author: fpsw   File: order.py    License: 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 3
Project: Servo   Author: fpsw   File: escalations.py    License: 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 4
Project: controller   Author: deis   File: serializers.py    License: MIT License 6 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 5
Project: polls-api   Author: apiaryio   File: cleanup.py    License: 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 6
Project: cookiecutter-django-iot   Author: aschn   File: test_models.py    License: 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 7
Project: cookiecutter-django-iot   Author: aschn   File: test_models.py    License: 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 8
Project: django-accounting   Author: dulacp   File: format_filters.py    License: 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 9
Project: django-accounting   Author: dulacp   File: models.py    License: 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 10
Project: django-accounting   Author: dulacp   File: views.py    License: 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 11
Project: django-accounting   Author: dulacp   File: views.py    License: 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
Project: djng   Author: djng   File: models.py    License: 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 13
Project: django-healthchecks   Author: mvantellingen   File: models.py    License: 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 14
Project: normandy   Author: mozilla   File: signing.py    License: 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 15
Project: open-synthesis   Author: twschiller   File: senddigest.py    License: 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 16
Project: pinax-documents   Author: pinax   File: models.py    License: MIT License 5 votes vote down vote up
def touch(self, user, commit=True):
        self.modified = timezone.now()
        self.modified_by = user
        if commit:
            if self.parent:
                self.parent.touch(user)
            self.save() 
Example 17
Project: pinax-documents   Author: pinax   File: models.py    License: MIT License 5 votes vote down vote up
def touch(self, user, commit=True):
        self.modified = timezone.now()
        self.modified_by = user
        if commit:
            if self.folder:
                self.folder.touch(user)
            self.save() 
Example 18
Project: pythonjobs.ie   Author: kimeraapp   File: models.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_actives(now=timezone.now()):
        limit = now - timedelta(days=120)
        return Job.objects.filter(
            status=1, created_at__gt=limit).order_by("-created_at").all() 
Example 19
Project: pythonjobs.ie   Author: kimeraapp   File: test_models.py    License: GNU General Public License v2.0 5 votes vote down vote up
def test_get_active_jobs_return_jobs_created_at_less_than_four_months(self):
        now = timezone.now() + timedelta(days=121)
        self.job.save()
        self.assertEqual(len(Job.get_actives(now)), 0) 
Example 20
Project: Servo   Author: fpsw   File: account.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clear_notifications(request):
    from datetime import datetime
    ts = [int(x) for x in request.GET.get('t').split('/')]
    ts = datetime(*ts, tzinfo=timezone.get_current_timezone())
    notif = request.user.notifications.filter(handled_at=None)
    notif.filter(triggered_at__lt=ts).update(handled_at=timezone.now())
    messages.success(request, _('All notifications cleared'))
    return redirect(request.META['HTTP_REFERER']) 
Example 21
Project: Servo   Author: fpsw   File: api.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def messages(request):
    """
    Responds to SMS status updates
    """
    from servo.messaging.sms import SMSJazzProvider, HQSMSProvider

    if not request.GET.get('id'):
        return HttpResponse('Thanks, but no thanks')

    m = get_object_or_404(Message, code=request.GET['id'])
    gw = Configuration.conf('sms_gateway')
    statusmap = HQSMSProvider.STATUSES

    if gw == 'jazz':
        statusmap = SMSJazzProvider.STATUSES

    status = statusmap[request.GET['status']]
    m.status = status[0]
    m.error = status[1]

    if m.status == 'DELIVERED':
        m.received_at = timezone.now()

    if m.status == 'FAILED':
        if m.note.order:
            uid = Configuration.conf('imap_act')
            if uid:
                user = User.objects.get(pk=uid)
                m.note.order.notify('sms_failed', m.error, user)

    m.save()

    return HttpResponse('OK') 
Example 22
Project: Servo   Author: fpsw   File: gsx.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def create_repair(request, order_id, device_id, type):
    """
    Creates a GSX repair for the specified SRO and device
    and redirects to the repair's edit page.
    """
    from datetime import timedelta
    from django.utils import timezone

    order = get_object_or_404(Order, pk=order_id)
    device = order.devices.get(pk=device_id)

    repair = Repair(order=order, created_by=request.user, device=device)
    timediff = timezone.now() - order.created_at

    if timediff.seconds <= 3600:
        repair.unit_received_at = order.created_at - timedelta(hours=1)
    else:
        repair.unit_received_at = order.created_at

    repair.reference = request.user.gsx_poprefix + order.code

    try:
        repair.gsx_account = GsxAccount.default(request.user, order.queue)
    except Exception as e:
        messages.error(request, e)
        return redirect(order)

    repair.repair_type = type
    repair.tech_id = request.user.tech_id
    repair.save()

    return redirect(edit_repair, order.pk, repair.pk) 
Example 23
Project: Servo   Author: fpsw   File: events.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def acknowledge(request, pk):
    e = Event.objects.get(pk=pk)
    e.handled_at = timezone.now()
    e.save()

    referer = request.META.get('HTTP_REFERER')

    if request.GET.get('return') == '0'and referer:
        return redirect(referer)

    return redirect(e.content_object.get_absolute_url()) 
Example 24
Project: Servo   Author: fpsw   File: servo_tags.py    License: BSD 2-Clause "Simplified" License 5 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 25
Project: Servo   Author: fpsw   File: repair.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def complete(self, user):
        """
        Mark our local copy of this GSX repair as complete
        """
        self.completed_at = timezone.now()
        self.completed_by = user
        self.save()

        msg = _('GSX repair %s marked complete') % self.confirmation
        self.order.notify('gsx_repair_complete', msg, user)

        queue = self.order.queue
        if queue.status_repair_completed:
            status = queue.status_repair_completed
            self.order.set_status(status, user) 
Example 26
Project: Servo   Author: fpsw   File: invoices.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def save(self, *args, **kwargs):
        invoice = self.invoice
        
        if self.method > 0:
            description = _(u'Payment for %0.2f received') % self.amount
            invoice.order.notify('paid', description, self.created_by)

        if invoice.paid_at is None:
            if invoice.get_payment_total() == invoice.total_gross:
                invoice.paid_at = timezone.now()
                invoice.save() 
Example 27
Project: Servo   Author: fpsw   File: order.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_title(self):
        """
        Returns a human-readable title for this order, based on various criteria
        """
        from django.utils.timesince import timesince
        now = timezone.now()
        moment_seconds = 120

        if self.closed_at:
            if (now - self.closed_at).seconds < moment_seconds:
                return _("Closed a moment ago")

            return _(u"Closed for %(time)s") % {'time': timesince(self.closed_at)}

        if self.status and self.status_started_at is not None:
            if (now - self.status_started_at).seconds < moment_seconds:
                return _(u"%s a moment ago") % self.status.status.title
            delta = timesince(self.status_started_at)
            d = {'status': self.status.status.title, 'time': delta}
            return _("%(status)s for %(time)s" % d)

        if self.user is None:
            if (now - self.created_at).seconds < moment_seconds:
                return _("Created a moment ago")
            return _("Unassigned for %(delta)s") % {'delta': timesince(self.created_at)}

        if self.in_progress():
            if (now - self.started_at).seconds < moment_seconds:
                return _("Started a moment ago")

            return _("Open for %(delta)s") % {'delta': timesince(self.started_at)} 
Example 28
Project: Servo   Author: fpsw   File: order.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def set_status(self, new_status, user):
        """
        Sets status of this order to new_status
        Status can only be set if order belongs to a queue!
        """
        if self.is_closed:
            return # fail silently

        if self.queue is None:
            raise ValueError(_('Order must belong to a queue to set status'))

        if isinstance(new_status, QueueStatus):
            status = new_status
        else:
            if int(new_status) == 0:
                return self.unset_status(user)

            status = QueueStatus.objects.get(pk=new_status)

        self.status = status
        self.status_name = status.status.title
        self.status_started_at = timezone.now()

        self.status_limit_green = status.get_green_limit()
        self.status_limit_yellow = status.get_yellow_limit()
        self.save()

        # Set up the OrderStatus
        OrderStatus.create(self, status, user)

        # trigger the notification
        self.notify("set_status", self.status_name, user) 
Example 29
Project: Servo   Author: fpsw   File: order.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def set_user(self, new_user, current_user):
        """
        Sets the assignee of this order to new_user
        """
        if self.state == self.STATE_CLOSED:
            raise ValueError(_('Closed orders cannot be modified'))

        state = self.STATE_OPEN

        if new_user is None:
            state = self.STATE_QUEUED
            event = _("Order unassigned")
            self.remove_follower(self.user)
        else:
            data = {'order': self.code, 'user': new_user.get_full_name()}
            event = _(u"Order %(order)s assigned to %(user)s") % data
            # The assignee should also be a follower
            self.add_follower(new_user)

        self.user = new_user
        self.state = state

        self.notify("set_user", event, current_user)

        if self.user is not None:
            self.location = new_user.location
            if self.started_by is None:
                self.started_by = new_user
                self.started_at = timezone.now()
                queue = self.queue
                if queue and queue.status_assigned:
                    self.set_status(queue.status_assigned, current_user)

        self.save() 
Example 30
Project: Servo   Author: fpsw   File: order.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def create(cls, order, queue_status, user):
        """
        Set status or order to queue_status.status
        """
        new_status = queue_status.status
        os = cls(order=order, status=new_status)
        os.started_by = user
        #os.started_at = timezone.now()

        os.green_limit = queue_status.get_green_limit()
        os.yellow_limit = queue_status.get_yellow_limit()

        os.save()

        prev = os.get_previous()

        if prev is None:
            return

        # set color of previous OS
        if prev.finished_by is None:
            prev.finished_by = user
            prev.finished_at = timezone.now()
            prev.duration = (prev.finished_at - prev.started_at).total_seconds()

        prev.badge = prev.get_badge()
        prev.save()