Python django.utils.timezone.activate() Examples

The following are 30 code examples for showing how to use django.utils.timezone.activate(). 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: anytask   Author: znick   File: views.py    License: MIT License 6 votes vote down vote up
def profile_settings(request):
    user = request.user
    user_profile = user.profile

    if request.method == 'POST':
        user_profile.show_email = 'show_email' in request.POST
        user_profile.send_my_own_events = 'send_my_own_events' in request.POST
        user_profile.location = request.POST.get('location', '')
        if 'geoid' in request.POST:
            tz = get_tz(request.POST['geoid'])
            user_profile.time_zone = tz
            request.session['django_timezone'] = tz
            timezone.activate(pytz.timezone(tz))
        user_profile.save()

        return HttpResponse("OK")

    context = {
        'user_profile': user_profile,
        'geo_suggest_url': settings.GEO_SUGGEST_URL
    }

    return render(request, 'user_settings.html', context) 
Example 2
Project: linkedevents   Author: City-of-Helsinki   File: test_notifications.py    License: MIT License 6 votes vote down vote up
def test_notification_template_rendering_empty_text_body(notification_template):
    context = {
        'subject_var': 'bar',
        'body_var': 'baz',
        'html_body_var': 'foo <b>bar</b> baz',
    }

    activate('fi')
    notification_template.body = ''
    notification_template.save()

    rendered = render_notification_template(NotificationType.TEST, context, 'fi')
    assert len(rendered) == 3
    assert rendered['subject'] == "testiotsikko, muuttujan arvo: bar!"
    assert rendered['body'] == "testihötömölöruumis, muuttujan arvo: foo bar baz!"
    assert rendered['html_body'] == "testi<b>hötömölö</b>ruumis, muuttujan arvo: foo <b>bar</b> baz!" 
Example 3
Project: linkedevents   Author: City-of-Helsinki   File: test_notifications.py    License: MIT License 6 votes vote down vote up
def test_notification_template_rendering_empty_html_body(notification_template):
    context = {
        'subject_var': 'bar',
        'body_var': 'baz',
        'html_body_var': 'foo <b>bar</b> baz',
    }

    activate('fi')
    notification_template.html_body = ''
    notification_template.save()

    rendered = render_notification_template(NotificationType.TEST, context, 'fi')
    assert len(rendered) == 3
    assert rendered['subject'] == "testiotsikko, muuttujan arvo: bar!"
    assert rendered['body'] == "testiruumis, muuttujan arvo: baz!"
    assert rendered['html_body'] == "" 
Example 4
Project: linkedevents   Author: City-of-Helsinki   File: test_notifications.py    License: MIT License 6 votes vote down vote up
def test_notification_template_format_datetime(notification_template):
    notification_template.body_en = "{{ datetime|format_datetime('en') }}"
    notification_template.save()

    dt = datetime(2020, 2, 22, 12, 0, 0, 0, pytz.utc)

    context = {
        'subject_var': 'bar',
        'datetime': dt,
        'html_body_var': 'foo <b>bar</b> baz',
    }

    timezone.activate(pytz.timezone('Europe/Helsinki'))

    rendered = render_notification_template(NotificationType.TEST, context, 'en')
    assert rendered['body'] == '22 Feb 2020 at 14:00' 
Example 5
Project: jinja2-django-tags   Author: MoritzS   File: tests.py    License: MIT License 6 votes vote down vote up
def test_localize(self):
        env = Environment(extensions=[DjangoL10n])
        template = env.from_string("{{ foo }}")
        context1 = {'foo': 1.23}
        date = datetime.datetime(2000, 10, 1, 14, 10, 12, tzinfo=timezone.utc)
        context2 = {'foo': date}

        translation.activate('en')
        self.assertEqual('1.23', template.render(context1))

        translation.activate('de')
        self.assertEqual('1,23', template.render(context1))

        translation.activate('es')
        timezone.activate('America/Argentina/Buenos_Aires')
        self.assertEqual('1 de Octubre de 2000 a las 11:10', template.render(context2))

        timezone.activate('Europe/Berlin')
        self.assertEqual('1 de Octubre de 2000 a las 16:10', template.render(context2))

        translation.activate('de')
        self.assertEqual('1. Oktober 2000 16:10', template.render(context2))

        timezone.activate('America/Argentina/Buenos_Aires')
        self.assertEqual('1. Oktober 2000 11:10', template.render(context2)) 
Example 6
Project: django-aws-template   Author: dkarchmer   File: timezoneMiddleware.py    License: MIT License 6 votes vote down vote up
def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        tzname = request.session.get('django_timezone')

        if not tzname:
            # Get it from the Account. Should hopefully happens once per session
            user = request.user
            if user and not user.is_anonymous:
                tzname = user.time_zone
                if tzname:
                    request.session['django_timezone'] = tzname

        if tzname:
            timezone.activate(pytz.timezone(tzname))
        else:
            timezone.deactivate()

        return response 
Example 7
Project: goals.zone   Author: meneses-pt   File: timezone.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __call__(self, request):
        if "HTTP_X_FORWARDED_FOR" in request.META:
            request.META["HTTP_X_PROXY_REMOTE_ADDR"] = request.META["REMOTE_ADDR"]
            parts = request.META["HTTP_X_FORWARDED_FOR"].split(",", 1)
            request.META["REMOTE_ADDR"] = parts[0]
        ip = request.META["REMOTE_ADDR"]
        g = GeoIP2()
        try:
            ip_response = g.city(ip)
            time_zone = ip_response['time_zone']
        except AddressNotFoundError:
            time_zone = None
        if time_zone:
            timezone_object = pytz.timezone(time_zone)
            timezone.activate(timezone_object)
        else:
            timezone.deactivate()
        return self.get_response(request) 
Example 8
Project: djongo   Author: nesdis   File: test_timezone.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_override(self):
        default = timezone.get_default_timezone()
        try:
            timezone.activate(ICT)

            with timezone.override(EAT):
                self.assertIs(EAT, timezone.get_current_timezone())
            self.assertIs(ICT, timezone.get_current_timezone())

            with timezone.override(None):
                self.assertIs(default, timezone.get_current_timezone())
            self.assertIs(ICT, timezone.get_current_timezone())

            timezone.deactivate()

            with timezone.override(EAT):
                self.assertIs(EAT, timezone.get_current_timezone())
            self.assertIs(default, timezone.get_current_timezone())

            with timezone.override(None):
                self.assertIs(default, timezone.get_current_timezone())
            self.assertIs(default, timezone.get_current_timezone())
        finally:
            timezone.deactivate() 
Example 9
Project: djongo   Author: nesdis   File: test_timezone.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_override(self):
        default = timezone.get_default_timezone()
        try:
            timezone.activate(ICT)

            with timezone.override(EAT):
                self.assertIs(EAT, timezone.get_current_timezone())
            self.assertIs(ICT, timezone.get_current_timezone())

            with timezone.override(None):
                self.assertIs(default, timezone.get_current_timezone())
            self.assertIs(ICT, timezone.get_current_timezone())

            timezone.deactivate()

            with timezone.override(EAT):
                self.assertIs(EAT, timezone.get_current_timezone())
            self.assertIs(default, timezone.get_current_timezone())

            with timezone.override(None):
                self.assertIs(default, timezone.get_current_timezone())
            self.assertIs(default, timezone.get_current_timezone())
        finally:
            timezone.deactivate() 
Example 10
Project: Servo   Author: fpsw   File: middleware.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def process_request(self, request):
        tzname = request.session.get('django_timezone')
        if tzname:
            timezone.activate(pytz.timezone(tzname))
        else:
            timezone.deactivate() 
Example 11
Project: django-sundial   Author: charettes   File: middleware.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        zone = self.get_timezone_from_request(request)
        if zone:
            timezone.activate(zone) 
Example 12
Project: anytask   Author: znick   File: timezone_middleware.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        if request.user.is_authenticated():
            tz = request.session.get('django_timezone',
                                     default=request.user.profile.time_zone) or settings.TIME_ZONE
            timezone.activate(tz)
        else:
            timezone.deactivate() 
Example 13
Project: anytask   Author: znick   File: send_notifications.py    License: MIT License 5 votes vote down vote up
def get_message(user, user_type, issue, events, from_email, domain):
    user_profile = user.profile

    if not user_profile.send_my_own_events:
        events = events.exclude(author_id=user.id)

    if not events:
        return ()

    lang = user_profile.language
    translation.activate(lang)
    timezone.activate(user_profile.time_zone)

    subject = (_(u'kurs') + u': {0} | ' + _(u'zadacha') + u': {1} | ' + _(u'student') + u': {2} {3}'). \
        format(issue.task.course.name, issue.task.get_title(lang), issue.student.last_name, issue.student.first_name)

    context = {
        "user": user,
        "domain": domain,
        "title": subject,
        "user_type": user_type,
        "issue": issue,
        "events": events,
        "STATIC_URL": settings.STATIC_URL,
    }

    plain_text = render_to_string('email_issue_notification.txt', context)
    html = render_to_string('email_issue_notification.html', context)
    translation.deactivate()
    timezone.deactivate()

    return subject, plain_text, html, from_email, [user.email] 
Example 14
Project: linkedevents   Author: City-of-Helsinki   File: test_notifications.py    License: MIT License 5 votes vote down vote up
def notification_template(notification_type):
    template = NotificationTemplate.objects.create(
        type=NotificationType.TEST,
        subject_en="test subject, variable value: {{ subject_var }}!",
        body_en="test body, variable value: {{ body_var }}!",
        html_body_en="test <b>HTML</b> body, variable value: {{ html_body_var }}!",
    )
    activate('fi')
    template.subject = "testiotsikko, muuttujan arvo: {{ subject_var }}!"
    template.body = "testiruumis, muuttujan arvo: {{ body_var }}!"
    template.html_body = "testi<b>hötömölö</b>ruumis, muuttujan arvo: {{ html_body_var }}!"
    template.save()

    return template 
Example 15
Project: jinja2-django-tags   Author: MoritzS   File: tests.py    License: MIT License 5 votes vote down vote up
def test_existing_finalize(self):
        finalize_mock = mock.Mock(side_effect=lambda s: s)

        class TestExtension(Extension):
            def __init__(self, environment):
                environment.finalize = finalize_mock

        env = Environment(extensions=[TestExtension, DjangoL10n])
        template = env.from_string("{{ foo }}")

        translation.activate('de')
        self.assertEqual('1,23', template.render({'foo': 1.23}))
        finalize_mock.assert_called_with(1.23) 
Example 16
Project: rankedftw   Author: andersroos   File: utils.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def localnow():
    """ Get the current datetime in the local timezone for the user
    (timezone set by timezone.activate())."""
    return timezone.localtime(utcnow(), timezone=timezone.get_current_timezone()) 
Example 17
Project: rankedftw   Author: andersroos   File: utils.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def localtoday():
    """ Get the current date in the local timezone for the user
    (timezone set by timezone.activate())."""
    return timezone.localtime(utcnow(), timezone=timezone.get_current_timezone()).date() 
Example 18
Project: hawkpost   Author: whitesmith   File: middleware.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        if request.user.is_authenticated():
            timezone.activate(request.user.timezone)
        else:
            timezone.deactivate() 
Example 19
Project: hawkpost   Author: whitesmith   File: middleware.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        if request.user.is_authenticated():
            translation.activate(request.user.language) 
Example 20
Project: palanaeum   Author: Palanaeum   File: middleware.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __call__(self, request):
        if request.user.is_authenticated:
            if hasattr(request.user, 'settings'):
                settings = request.user.settings
            else:
                from palanaeum.models import UserSettings
                settings = UserSettings.objects.create(user=request.user)
            tzname = settings.timezone
            timezone.activate(pytz.timezone(tzname))
        else:
            timezone.deactivate()

        response = self.get_response(request)

        return response 
Example 21
Project: janeway   Author: BirkbeckCTP   File: middleware.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def process_request(self, request):
        if request.user.is_authenticated and request.user.preferred_timezone:
            tzname = request.user.preferred_timezone
        elif request.session.get("janeway_timezone"):
            tzname = request.session["janeway_timezone"]
        else:
            tzname = None

        try:
            request.timezone = tzname
            if tzname is not None:
                timezone.activate(pytz.timezone(tzname))
                logger.debug("Activated timezone %s" % tzname)
        except Exception as e:
            logger.warning("Failed to activate timezone %s: %s" % (tzname, e)) 
Example 22
Project: bennedetto   Author: arecker   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def activate_timezone(self):
        timezone.activate(self.timezone) 
Example 23
Project: Spirit   Author: nitely   File: tests.py    License: MIT License 5 votes vote down vote up
def test_timezone(self):
        """
        Should activate the user timezone
        """
        timezone.deactivate()
        utils.login(self)
        req = RequestFactory().get('/')
        req.user = self.user
        time_zone = 'America/Argentina/Buenos_Aires'
        self.user.st.timezone = time_zone

        self.assertEqual(timezone.get_current_timezone().zone, 'UTC')
        middleware.TimezoneMiddleware().process_request(req)
        self.assertEqual(timezone.get_current_timezone().zone, time_zone) 
Example 24
Project: Spirit   Author: nitely   File: tests.py    License: MIT License 5 votes vote down vote up
def test_timezone_bad_tz(self):
        timezone.deactivate()
        utils.login(self)
        req = RequestFactory().get('/')
        req.user = self.user
        self.user.st.timezone = 'badtimezone'

        time_zone = 'America/Argentina/Buenos_Aires'
        timezone.activate(time_zone)
        self.assertEqual(timezone.get_current_timezone().zone, time_zone)
        middleware.TimezoneMiddleware().process_request(req)
        self.assertEqual(timezone.get_current_timezone().zone, 'UTC') 
Example 25
Project: Spirit   Author: nitely   File: tests.py    License: MIT License 5 votes vote down vote up
def test_timezone_anonymous_user(self):
        class AnonymUserMock(object):
            @property
            def is_authenticated(self):
                return False

        timezone.deactivate()
        req = RequestFactory().get('/')
        req.user = AnonymUserMock()

        time_zone = 'America/Argentina/Buenos_Aires'
        timezone.activate(time_zone)
        self.assertEqual(timezone.get_current_timezone().zone, time_zone)
        middleware.TimezoneMiddleware().process_request(req)
        self.assertEqual(timezone.get_current_timezone().zone, 'UTC') 
Example 26
Project: Spirit   Author: nitely   File: middleware.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        if not request.user.is_authenticated:
            timezone.deactivate()
            return

        try:
            timezone.activate(request.user.st.timezone)
        except pytz.exceptions.UnknownTimeZoneError:
            timezone.deactivate()
            logger.error(
                '%s is not a valid timezone.', request.user.st.timezone) 
Example 27
Project: richie   Author: openfun   File: test_fields_datetimerange.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        """
        Make sure all our tests are timezone-agnostic. As we're using datetimes, our tests would
        be dependent upon the host machine's timezone otherwise.
        """
        timezone.activate("UTC") 
Example 28
Project: richie   Author: openfun   File: test_viewsets_courses.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        """
        Make sure all our tests are timezone-agnostic. Some of them parse ISO datetimes and those
        would be broken if we did not enforce timezone normalization.
        """
        super().setUp()
        timezone.activate(pytz.utc) 
Example 29
Project: baobab   Author: Gandi   File: set_current_timezone.py    License: GNU General Public License v3.0 5 votes vote down vote up
def process_request(self, request):
        if request.user.is_authenticated():
            timezone.activate(pytz.timezone(str(request.user.timezone)))
        else:
            timezone.activate(settings.TIME_ZONE) 
Example 30
Project: django-htk   Author: hacktoolkit   File: classes.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        #django_timezone = request.session.get(DJANGO_TIMEZONE, None)
        #if not django_timezone and request.user.is_authenticated:
        if request.user.is_authenticated:
            user = request.user
            django_timezone = user.profile.get_django_timezone()
            # <DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD> is not JSON serializable
            #request.session[DJANGO_TIMEZONE] = django_timezone
        else:
            django_timezone = None
        if django_timezone:
            timezone.activate(django_timezone)