|
| 1 | +title: django.utils.timezone Examples |
| 2 | +category: page |
| 3 | +slug: django-utils-timezone-examples |
| 4 | +sortorder: 50020 |
| 5 | +toc: False |
| 6 | +sidebartitle: django.utils.timezone |
| 7 | +meta: Python code examples for timezone-related classes and functions provided by the Django codebase. |
| 8 | + |
| 9 | + |
| 10 | +# django.utils.timezone Examples |
| 11 | +[timezone.py](https://github.com/django/django/blob/master/django/utils/timezone.py) |
| 12 | +is a source file within the [Django](/django.html) project that contains |
| 13 | +timezone-related classes and functions that are helpful when building |
| 14 | +web applications. |
| 15 | + |
| 16 | +## Example 1 from django-cms |
| 17 | +[django-cms](https://github.com/divio/django-cms) |
| 18 | +([project website](https://www.django-cms.org/en/)) is a Python-based |
| 19 | +content management system (CMS) [library](https://pypi.org/project/django-cms/) |
| 20 | +for use with Django web apps that is open sourced under the |
| 21 | +[BSD 3-Clause "New" License](https://github.com/divio/django-cms/blob/develop/LICENSE). |
| 22 | + |
| 23 | +[**django-cms/cms/models/query.py**](https://github.com/divio/django-cms/blob/develop/cms/models/query.py) |
| 24 | + |
| 25 | +```python |
| 26 | +# -*- coding: utf-8 -*- |
| 27 | +from django.db.models import Q |
| 28 | +~~from django.utils import timezone |
| 29 | + |
| 30 | +from treebeard.mp_tree import MP_NodeQuerySet |
| 31 | + |
| 32 | +from cms.publisher.query import PublisherQuerySet |
| 33 | +from cms.exceptions import NoHomeFound |
| 34 | + |
| 35 | + |
| 36 | +class PageQuerySet(PublisherQuerySet): |
| 37 | + |
| 38 | + def on_site(self, site=None): |
| 39 | + from cms.utils import get_current_site |
| 40 | + |
| 41 | + if site is None: |
| 42 | + site = get_current_site() |
| 43 | + return self.filter(node__site=site) |
| 44 | + |
| 45 | + def published(self, site=None, language=None): |
| 46 | +~~ now = timezone.now() |
| 47 | + if language: |
| 48 | +~~ pub = self.on_site(site).filter( |
| 49 | +~~ Q(publication_date__lte=now) | Q(publication_date__isnull=True), |
| 50 | +~~ Q(publication_end_date__gt=now) | Q(publication_end_date__isnull=True), |
| 51 | +~~ title_set__published=True, title_set__language=language, |
| 52 | + ) |
| 53 | + else: |
| 54 | +~~ pub = self.on_site(site).filter( |
| 55 | +~~ Q(publication_date__lte=now) | Q(publication_date__isnull=True), |
| 56 | +~~ Q(publication_end_date__gt=now) | Q(publication_end_date__isnull=True), |
| 57 | +~~ title_set__published=True, |
| 58 | + ) |
| 59 | + return pub.exclude(title_set__publisher_state=4) |
| 60 | +``` |
0 commit comments