Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions src/filters/dates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -514,8 +514,9 @@ fn try_native(
fmt: &str,
date_only_ok: bool,
) -> PyResult<Option<String>> {
// Exact datetime.datetime only (cast would also accept subclasses).
if value.get_type().as_ptr() != py.get_type::<PyDateTime>().as_ptr() {
// Exact datetime.datetime or stock `tz.datetimeobject` only (cast
// would also accept arbitrary subclasses).
if !crate::filters::is_stock_datetime(value) {
return Ok(None);
}
let dt = value.cast::<PyDateTime>()?;
Expand Down Expand Up @@ -543,16 +544,16 @@ fn try_native(
run_program(py, fmt, &fields)
}

/// `dateformat.format(value, fmt)` for an EXACT `datetime.datetime` or
/// `datetime.date` (`localize`'s `date_format` step); `Ok(None)` → stock
/// `dateformat.format(value, fmt)` for an EXACT `datetime.datetime` (or
/// stock `tz.datetimeobject`) or `datetime.date` (`localize`'s `date_format` step); `Ok(None)` → stock
/// Python path (timezone/isoformat specifiers, time specifiers on a plain
/// date, other types).
pub(crate) fn format_exact(
py: Python<'_>,
value: &Bound<'_, PyAny>,
fmt: &str,
) -> PyResult<Option<String>> {
if value.get_type().as_ptr() == py.get_type::<PyDateTime>().as_ptr() {
if crate::filters::is_stock_datetime(value) {
return try_native(py, value, fmt, true);
}
if value.get_type().as_ptr() != py.get_type::<PyDate>().as_ptr() {
Expand Down
95 changes: 95 additions & 0 deletions src/filters/humanize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -472,3 +472,98 @@ fn timesince<'py>(
let sep = tr.gettext(", ")?;
sep.call_method1(pyo3::intern!(py, "join"), (parts,))
}

/// The stock Python `ordinal` (fallback for everything but plain ints).
fn py_ordinal(py: Python<'_>) -> PyResult<&Bound<'_, PyAny>> {
static F: PyOnceLock<Py<PyAny>> = PyOnceLock::new();
Ok(F.get_or_try_init(py, || -> PyResult<Py<PyAny>> {
Ok(py
.import("django.contrib.humanize.templatetags.humanize")?
.getattr("ordinal")?
.unbind())
})?
.bind(py))
}

/// `True` while the humanize module's `pgettext` / `mark_safe` globals are
/// the stock functions (`ordinal` resolves both at call time).
fn ordinal_globals_stock(py: Python<'_>) -> PyResult<bool> {
static G: PyOnceLock<(Py<pyo3::types::PyDict>, Py<PyAny>, Py<PyAny>)> = PyOnceLock::new();
let (globals, pgettext, mark_safe) = G.get_or_try_init(py, || -> PyResult<_> {
Ok((
py.import("django.contrib.humanize.templatetags.humanize")?
.dict()
.unbind(),
py.import("django.utils.translation")?.getattr("pgettext")?.unbind(),
py.import("django.utils.safestring")?.getattr("mark_safe")?.unbind(),
))
})?;
let globals = globals.bind(py);
let same = |name: &str, f: &Py<PyAny>| -> PyResult<bool> {
Ok(globals.get_item(name)?.is_some_and(|g| g.is(f.bind(py))))
};
Ok(same("pgettext", pgettext)? && same("mark_safe", mark_safe)?)
}

/// `(context, msgid)` of the one ordinal template stock picks for `n >= 0`
/// (it translates all ten `n % 10` templates, then indexes one: the other
/// nine lookups have no visible effect).
fn ordinal_msg(n: i64) -> (&'static str, &'static str) {
const BY_LAST: [(&str, &str); 10] = [
("ordinal 0", "{}th"),
("ordinal 1", "{}st"),
("ordinal 2", "{}nd"),
("ordinal 3", "{}rd"),
("ordinal 4", "{}th"),
("ordinal 5", "{}th"),
("ordinal 6", "{}th"),
("ordinal 7", "{}th"),
("ordinal 8", "{}th"),
("ordinal 9", "{}th"),
];
if n == 1 {
("ordinal is 1", "{}st")
} else if matches!(n % 100, 11..=13) {
("ordinal 11, 12, 13", "{}th")
} else {
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // 0..=9
BY_LAST[(n % 10) as usize]
}
}

/// `ordinal(value)` for an exact `int` that fits `i64` (`int(value)` is
/// the identity): negatives → plain `str(value)`, else the selected
/// template translated through `Translator::pgettext`, `.format(value)`
/// (natively when the translation holds exactly one `{}` and no other
/// brace), then `mark_safe`. Other inputs or patched module globals take
/// the Python function.
pub(crate) fn ordinal<'py>(
_rc: &mut Rctx<'py>,
input: &Bound<'py, PyAny>,
args: &[Bound<'py, PyAny>],
_ae: Option<bool>,
) -> PyResult<Bound<'py, PyAny>> {
let py = input.py();
if args.is_empty() && input.is_exact_instance_of::<PyInt>() {
if let Ok(n) = input.extract::<i64>() {
if n < 0 {
return Ok(PyString::new(py, &n.to_string()).into_any());
}
if ordinal_globals_stock(py)? {
let (context, msgid) = ordinal_msg(n);
let tmpl = super::Translator::new(py).pgettext(context, msgid)?;
let formatted = match tmpl.cast_exact::<PyString>().ok().and_then(|s| {
let s = s.to_str().ok()?;
let (pre, post) = s.split_once("{}")?;
let plain = |p: &str| !p.contains(['{', '}']);
(plain(pre) && plain(post)).then(|| format!("{pre}{n}{post}"))
}) {
Some(s) => PyString::new(py, &s).into_any(),
None => tmpl.call_method1(pyo3::intern!(py, "format"), (input,))?,
};
return crate::render::value::mark_safe_bound(&formatted);
}
}
}
py_ordinal(py)?.call1((input,).into_pyobject(py)?.add_args(args)?)
}
69 changes: 63 additions & 6 deletions src/filters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ fn humanize_native(func: &Bound<'_, PyAny>) -> Option<NativeFn> {
match qualname.as_str() {
"intcomma" => Some(humanize::intcomma),
"naturaltime" => Some(humanize::naturaltime),
"ordinal" => Some(humanize::ordinal),
_ => None,
}
}
Expand Down Expand Up @@ -684,13 +685,63 @@ pub(crate) fn local_value<'py>(
.ok()
}

/// `django.templatetags.tz.datetimeobject`: the bare `datetime` subclass
/// the `localtime`/`utc`/`timezone` filters return (its only addition is
/// the `convert_to_local_time` instance attribute). Looked up in
/// `sys.modules` rather than imported (no instance can exist before the
/// module loads) and cached once found, only if the class body is empty
/// at that point (a class patched by then keeps the Python path).
fn tz_datetimeobject(py: Python<'_>) -> Option<&Bound<'_, pyo3::types::PyType>> {
static TY: PyOnceLock<Py<pyo3::types::PyType>> = PyOnceLock::new();
if let Some(t) = TY.get(py) {
return Some(t.bind(py));
}
let modules = py.import("sys").ok()?.getattr("modules").ok()?;
let tz = modules.get_item("django.templatetags.tz").ok()?;
let ty = tz.getattr("datetimeobject").ok()?.cast_into::<pyo3::types::PyType>().ok()?;
let plain = ty.getattr("__dict__").ok()?.try_iter().ok()?.all(|k| {
k.ok().and_then(|k| k.extract::<String>().ok()).is_some_and(|k| {
matches!(
k.as_str(),
"__module__"
| "__qualname__"
| "__doc__"
| "__dict__"
| "__weakref__"
| "__firstlineno__"
| "__static_attributes__"
)
})
});
if !plain || ty.getattr("__bases__").ok()?.len().ok()? != 1 {
return None;
}
let _ = TY.set(py, ty.unbind());
TY.get(py).map(|t| t.bind(py))
}

/// `True` for an exact `datetime.datetime` or a stock `tz.datetimeobject`
/// — the types the native datetime paths treat alike (same C layout, no
/// overridden methods).
pub(crate) fn is_stock_datetime(value: &Bound<'_, PyAny>) -> bool {
use pyo3::types::PyDateTime;
let py = value.py();
let ty = value.get_type();
if ty.as_ptr() == py.get_type::<PyDateTime>().as_ptr() {
return true;
}
value.is_instance_of::<PyDateTime>() && tz_datetimeobject(py).is_some_and(|t| ty.is(t))
}

/// Native `django.utils.timezone.template_localtime(value, use_tz)` for an
/// EXACT `datetime.datetime`; `Ok(None)` means "call the Python function"
/// (other types, or state that can't be read natively).
/// exact `datetime.datetime` or a stock `tz.datetimeobject`; `Ok(None)`
/// means "call the Python function" (other types, or state that can't be
/// read natively).
///
/// Stock: convert iff `use_tz` (or `settings.USE_TZ` when None) and
/// `value.utcoffset() is not None` (an exact datetime has no
/// `convert_to_local_time` attribute), via `value.astimezone(tz)` with
/// Stock: convert iff `use_tz` (or `settings.USE_TZ` when None),
/// `value.utcoffset() is not None` and
/// `getattr(value, "convert_to_local_time", True)` (absent on an exact
/// datetime), via `value.astimezone(tz)` with
/// `tz = getattr(_active, "value", get_default_timezone())`. The active
/// zone is read from `timezone._active`'s contextvar (~0.2 µs) instead of
/// the asgiref `Local.__getattr__` chain (~5 µs).
Expand All @@ -700,7 +751,7 @@ pub(crate) fn template_localtime_exact<'py>(
) -> PyResult<Option<Bound<'py, PyAny>>> {
use pyo3::types::{PyDateTime, PyTzInfoAccess};
let py = value.py();
if value.get_type().as_ptr() != py.get_type::<PyDateTime>().as_ptr() {
if !is_stock_datetime(value) {
return Ok(None);
}
let dt = value.cast::<PyDateTime>()?;
Expand All @@ -718,6 +769,12 @@ pub(crate) fn template_localtime_exact<'py>(
if !use_tz || value.call_method0(pyo3::intern!(py, "utcoffset"))?.is_none() {
return Ok(Some(value.clone()));
}
if value.get_type().as_ptr() != py.get_type::<PyDateTime>().as_ptr() {
match value.getattr_opt(pyo3::intern!(py, "convert_to_local_time"))? {
Some(c) if !c.is_truthy()? => return Ok(Some(value.clone())),
_ => {}
}
}
let Some(tz) = current_timezone(py)? else {
return Ok(None);
};
Expand Down
8 changes: 5 additions & 3 deletions src/render/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1358,7 +1358,7 @@ fn finish(rctx: &Rctx<'_>, s: String) -> PyResult<String> {
/// and without `decimal_pos`: `str(value)` with the locale
/// `DECIMAL_SEPARATOR` substituted (`str(value)` when `use_l10n` is
/// False). Exponent notation, non-finite or huge `Decimal`s keep Python;
/// - exact `datetime` / `date`: `template_localtime` is the identity for
/// - exact `datetime` (or stock `tz.datetimeobject`) / `date`: `template_localtime` is the identity for
/// naive values (aware ones take the real call), then `date_format` with
/// `DATETIME_FORMAT` / `DATE_FORMAT` through the native dateformat port;
/// - any other object whose class is none of `str`/`int`/`float`/
Expand Down Expand Up @@ -1431,13 +1431,15 @@ fn native_render<'py>(
}
return finish(rctx, out).map(Native::Done);
}
let is_dt = ty.is(vt.datetime.bind(py));
// Stock `tz.datetimeobject` (the `localtime`/`timezone` filters'
// result) renders exactly like a datetime.
let is_dt = ty.is(vt.datetime.bind(py)) || crate::filters::is_stock_datetime(value);
if is_dt || ty.is(vt.date.bind(py)) {
let mut v = value.clone();
if is_dt && !value.cast::<PyDateTime>()?.get_tzinfo().is_none() {
// Possibly aware: `template_localtime` decides.
v = template_localtime(rctx, value.clone())?;
if !v.get_type().is(vt.datetime.bind(py)) {
if !crate::filters::is_stock_datetime(&v) {
return Ok(Native::Localtimed(v));
}
}
Expand Down
103 changes: 103 additions & 0 deletions tests/test_realpage.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
"i18n": "django.templatetags.i18n",
"humanize": "django.contrib.humanize.templatetags.humanize",
"static": "django.templatetags.static",
"tz": "django.templatetags.tz",
"l10n": "django.templatetags.l10n",
}
ENGINES = {"stock": StockEngine(libraries=LIBS), "rust": RustEngine(libraries=LIBS)}
LANGS = [None, "de", "fr", "es", "ja"]
Expand Down Expand Up @@ -478,3 +480,104 @@ def test_static(src, static_url, installed):
# `STATIC_URL` is read when the storage is set up.
staticfiles_storage._wrapped = empty
assert_parity("{% load static %}" + src, ctx)


def tz_filter_values():
from django.templatetags.tz import datetimeobject

aware = datetime.datetime(2024, 3, 10, 7, 30, 15, 123456, tzinfo=datetime.timezone.utc)
forced = datetimeobject(2024, 7, 1, 23, 5, tzinfo=datetime.timezone.utc)
forced.convert_to_local_time = True
flagged = datetimeobject(2024, 7, 1, 23, 5, tzinfo=datetime.timezone.utc)
flagged.convert_to_local_time = 0
return [
aware,
aware.astimezone(zoneinfo.ZoneInfo("Asia/Kolkata")),
datetime.datetime(2024, 11, 3, 1, 30), # naive, DST fold in Chicago
datetime.date(2024, 1, 2),
# Constructed directly: no instance flag (converts), set True, falsy.
datetimeobject(2024, 7, 1, 23, 5, tzinfo=datetime.timezone.utc),
datetimeobject(2024, 7, 1, 23, 5),
forced,
flagged,
"2024-01-01",
None,
]


TZ_FILTER_CASES = {
"localtime": "{{ v|localtime }}",
"utc": "{{ v|utc }}",
"timezone-name": "{{ v|timezone:'Europe/Paris' }}",
"timezone-obj": "{{ v|timezone:tz }}",
"timezone-bad": "[{{ v|timezone:'Nowhere/Nope' }}]",
"localtime-off": "{% localtime off %}{{ v }}|{{ v|localtime }}{% endlocaltime %}",
"date": "{{ v|timezone:'Asia/Tokyo'|date:'Y-m-d H:i:s.u e O T U c r' }}",
"date-default": "{{ v|localtime|date }}|{{ v|utc|time }}|{{ v|utc|time:'H:i e' }}",
"plain": "{{ v }}",
"l10n-off": "{% localize off %}{{ v|utc }}{% endlocalize %}",
"autoescape-off": "{% autoescape off %}{{ v|localtime }}{% endautoescape %}",
}


@pytest.mark.parametrize("use_tz", [True, False])
@pytest.mark.parametrize("lang", [None, "de", "ja"])
@pytest.mark.parametrize("src", TZ_FILTER_CASES.values(), ids=TZ_FILTER_CASES.keys())
def test_tz_filters(src, lang, use_tz):
"""`localtime`/`utc`/`timezone` return a `tz.datetimeobject`, which the
native datetime paths treat like an exact datetime."""
engines_libs = "{% load tz l10n %}"
ctx_tz = zoneinfo.ZoneInfo("Australia/Adelaide")
with override_settings(USE_TZ=use_tz):
for v in tz_filter_values():
for active in (None, "Pacific/Auckland"):
assert_parity(engines_libs + src, {"v": v, "tz": ctx_tz}, lang=lang, tz=active)


def test_tz_datetimeobject_subclass_stays_python():
"""A further subclass of `datetimeobject` isn't the stock type."""
from django.templatetags.tz import datetimeobject

class Odd(datetimeobject):
def __str__(self):
return "odd"

v = Odd(2024, 7, 1, 23, 5, tzinfo=datetime.timezone.utc)
assert_parity("{% load tz %}{{ v }}|{{ v|date:'c' }}|{{ v|localtime }}", {"v": v}, lang="de")


ORDINAL_VALUES = [
*range(0, 30), 100, 101, 102, 103, 104, 111, 112, 113, 114, 121, 1011, 2**62, 2**63, 10**30,
-1, -11, -(2**63), True, False, "3", "x", 3.7, Decimal("12"), None, [],
]


@pytest.mark.parametrize("lang", [None, "de", "fr", "es", "ja", "nl", "ar"])
def test_ordinal(lang):
src = (
"{% load humanize %}{% for v in vals %}[{{ v|ordinal }}|{{ v|ordinal|length }}"
"|{% autoescape off %}{{ v|ordinal }}{% endautoescape %}]{% endfor %}"
)
assert_parity(src, {"vals": ORDINAL_VALUES}, lang=lang)


def test_ordinal_i18n_off():
with override_settings(USE_I18N=False):
src = "{% load humanize %}{% for v in vals %}[{{ v|ordinal }}]{% endfor %}"
assert_parity(src, {"vals": ORDINAL_VALUES}, lang="de")


@pytest.mark.parametrize("tmpl", ["<{}>", "{}{{x}}", "{0}.", "no placeholder", "{}-{}"])
def test_ordinal_patched_globals(tmpl):
"""Patched `pgettext` (any template shape) / `mark_safe` keep stock output."""
from django.contrib.humanize.templatetags import humanize

src = "{% load humanize %}{% for v in vals %}[{{ v|ordinal }}]{% endfor %}"
orig_pg, orig_ms = humanize.pgettext, humanize.mark_safe
humanize.pgettext = lambda ctx, msg: tmpl
try:
assert_parity(src, {"vals": [1, 2, 11, 23]}, lang="de")
humanize.mark_safe = str
assert_parity(src, {"vals": [1, 2, 11, 23]}, lang="de")
finally:
humanize.pgettext, humanize.mark_safe = orig_pg, orig_ms
Loading