django-validation-lifecycle 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.5
2
+ Name: django-validation-lifecycle
3
+ Version: 0.1.0
4
+ Summary: Declarative validation rules for Django models.
5
+ Project-URL: Homepage, https://github.com/Mohamed-Kaizen/django-validation-lifecycle
6
+ Project-URL: Source, https://github.com/Mohamed-Kaizen/django-validation-lifecycle
7
+ Author-email: Mohamed Nesredin <mohamednesredin19@hotmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Framework :: Django
12
+ Classifier: Framework :: Django :: 6.0
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Requires-Python: >=3.12
20
+ Requires-Dist: django>=6.0
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
23
+ Requires-Dist: pytest-django>=4.8; extra == 'dev'
24
+ Requires-Dist: pytest-mock>=3.14; extra == 'dev'
25
+ Requires-Dist: pytest>=8; extra == 'dev'
26
+ Provides-Extra: docs
27
+ Requires-Dist: mkdocstrings[python]>=0.27; extra == 'docs'
28
+ Requires-Dist: pymdown-extensions>=10.0; extra == 'docs'
29
+ Requires-Dist: zensical>=0.0.59; extra == 'docs'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # django-validation-lifecycle
33
+
34
+ **Declarative validation rules for Django models.**
35
+
36
+ Stop scattering `clean()` methods and `full_clean()` calls across your
37
+ codebase. Describe rules on the model, get validation in `save()`,
38
+ system checks, and an audit command — for free.
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ pip install django-validation-lifecycle
44
+ ```
45
+
46
+ Requires Python 3.12+ and Django 6.0+.
47
+
48
+ ## Quick example
49
+
50
+ ```python
51
+ from django.core.exceptions import ValidationError
52
+ from django.db import models
53
+ from validation_lifecycle import AutoValidateModelMixin, validate
54
+
55
+
56
+ class CustomUser(AutoValidateModelMixin):
57
+ username = models.CharField(max_length=100)
58
+ email = models.EmailField()
59
+
60
+ @validate("username", has_changed=True, skip_if_blank=True)
61
+ def username_validate(self) -> None:
62
+ if self.username.lower() in {"admin", "root"}:
63
+ raise ValidationError("Reserved username.")
64
+
65
+ @validate("email")
66
+ def email_validate(self) -> None:
67
+ if not self.email.endswith("@example.com"):
68
+ raise ValidationError("Must be an @example.com address.")
69
+ ```
70
+
71
+ Add `"validation_lifecycle"` to `INSTALLED_APPS`, and you get:
72
+
73
+ - **Save-time validation** — `CustomUser.objects.create(...)` runs `full_clean()` before writing.
74
+ - **Change-aware rules** — `has_changed=True` skips the rule when the field didn't change.
75
+ - **System checks** — `python manage.py check` catches missing mixins, bad field refs, and async `clean()` traps.
76
+ - **Audit command** — `python manage.py vl_check` scans existing rows against current rules.
77
+ - **Async support** — `async def` rules run under `afull_clean()` / `asave()`.
78
+
79
+ ## Features
80
+
81
+ - **Declarative** — rules live next to the fields they check.
82
+ - **Change-aware** — `has_changed=True` only fires on real changes.
83
+ - **Async-ready** — first-class support for `async def` rules.
84
+ - **Inheritance-friendly** — `@no_validate` removes an inherited rule.
85
+ - **Auditable** — `vl_check` scans existing data against current rules.
86
+ - **Safe by default** — system checks catch the common traps.
87
+
88
+ ## Documentation
89
+
90
+ Full docs at **https://Mohamed-Kaizen.github.io/django-validation-lifecycle/**
91
+
92
+ - [Quickstart](https://Mohamed-Kaizen.github.io/django-validation-lifecycle/quickstart/)
93
+ - [Decorators reference](https://Mohamed-Kaizen.github.io/django-validation-lifecycle/guide/decorators/)
94
+ - [System checks](https://Mohamed-Kaizen.github.io/django-validation-lifecycle/guide/checks/)
95
+
96
+ ## License
97
+
98
+ MIT
@@ -0,0 +1,17 @@
1
+ validation_lifecycle/__init__.py,sha256=HLYcqXz4srWXOubVE6guU9Wq8KdoaEZX0nGrnkxx2zw,325
2
+ validation_lifecycle/apps.py,sha256=EcDjiQujpd8pC6SMcrJXZkmyVDyoE-PNjC2O6aLsdH0,556
3
+ validation_lifecycle/checks.py,sha256=Tjxj3lLbKLSkrdpB3_jfAMoMvzUq9tNYLRbq2L-fquc,8996
4
+ validation_lifecycle/conf.py,sha256=6MNUKSVuX_msaB5GxCDnswXyklekGmZHmkxCfNSnAok,1458
5
+ validation_lifecycle/decorators.py,sha256=AvpvZnFB5koFDknRvGpfhwAEMByHW52geoXcAWfdt-M,3325
6
+ validation_lifecycle/mixins.py,sha256=FuhHYGRSFlJr5f-I2vXjUfkNYpcmmKPp5cKYAsECPwE,13951
7
+ validation_lifecycle/registry.py,sha256=9yv5oWAVW9aqNH0fV2Jb9Q2l6CIt7kkMYqpQu-ximjA,1075
8
+ validation_lifecycle/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ validation_lifecycle/contrib/createsuperuser.py,sha256=hmM4gkjOrdLSXpyoYrmFVx3UkjOr8RBf8Lz0-oKALA4,769
10
+ validation_lifecycle/management/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ validation_lifecycle/management/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ validation_lifecycle/management/commands/vl_check.py,sha256=z8qgYIIGqY0SLpy4TsS5cblwJ-pmICjR4NyDJTuiFv0,3492
13
+ validation_lifecycle/migrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ django_validation_lifecycle-0.1.0.dist-info/METADATA,sha256=zuTtrw3QRB3JGD-BD6boN5kccXZj-5Tgynut2q4LT4M,3786
15
+ django_validation_lifecycle-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
16
+ django_validation_lifecycle-0.1.0.dist-info/licenses/LICENSE,sha256=PPtjMJW9_3gCuaOZdwZgNHbJtbgjoQj4NMHW2yc8JIg,1072
17
+ django_validation_lifecycle-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohamed Nesredin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,14 @@
1
+ """Declarative validation for Django models."""
2
+
3
+ from .decorators import ValidateRule, validate, no_validate
4
+ from .mixins import AutoValidateModelMixin, ValidationModelMixin
5
+
6
+ __all__ = [
7
+ "AutoValidateModelMixin",
8
+ "ValidateRule",
9
+ "ValidationModelMixin",
10
+ "no_validate",
11
+ "validate",
12
+ ]
13
+
14
+ __version__ = "0.1.0"
@@ -0,0 +1,16 @@
1
+ """App configuration for validation_lifecycle."""
2
+
3
+ from django.apps import AppConfig
4
+ from django.utils.translation import gettext_lazy as _
5
+
6
+
7
+ class ValidationLifecycleConfig(AppConfig):
8
+ """Django app config — optional but enables system checks and commands."""
9
+
10
+ name = "validation_lifecycle"
11
+ verbose_name = _("Validation Lifecycle")
12
+ default_auto_field = "django.db.models.BigAutoField"
13
+
14
+ def ready(self) -> None:
15
+ """Import checks module so Django discovers system checks."""
16
+ from . import checks # noqa: F401, PLC0415
@@ -0,0 +1,260 @@
1
+ """System checks for common misconfigurations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+
7
+ from django.apps import apps
8
+ from django.core import checks
9
+ from django.db import models
10
+
11
+ from .conf import DEFAULTS, vl_settings
12
+ from .decorators import _VALIDATE_ATTR, _VALIDATE_REMOVED, ValidateRule
13
+ from .mixins import AutoValidateModelMixin, ValidationModelMixin
14
+
15
+
16
+ # ---------------------------------------------------------------------------
17
+ # Error / Warning factories
18
+ #
19
+ # ``checks.Error`` and ``checks.Warning`` are plain dataclasses — they do not
20
+ # template their messages, so we construct a fresh instance at each use-site
21
+ # with the message already formatted.
22
+ # ---------------------------------------------------------------------------
23
+ def _e001(model: str) -> checks.Error:
24
+ return checks.Error(
25
+ f"Model {model} defines @validate rules (directly or via abstract/mixin "
26
+ f"ancestors) but does not inherit from ValidationModelMixin or "
27
+ f"AutoValidateModelMixin, so the rules will never run.",
28
+ id="validation_lifecycle.E001",
29
+ )
30
+
31
+
32
+ def _e002(model: str, method: str, field: str) -> checks.Error:
33
+ return checks.Error(
34
+ f"Validation rule {method} on {model} references field '{field}' "
35
+ f"which does not exist on the model.",
36
+ id="validation_lifecycle.E002",
37
+ )
38
+
39
+
40
+ def _e003(model: str) -> checks.Error:
41
+ return checks.Error(
42
+ f"Model {model} inherits from ValidationModelMixin but places it "
43
+ f"AFTER the model base class in its MRO (e.g. `class Foo(models.Model, "
44
+ f"ValidationModelMixin)`). The mixin's full_clean() is bypassed; move "
45
+ f"the mixin before the model base.",
46
+ id="validation_lifecycle.E003",
47
+ )
48
+
49
+
50
+ def _e004(model: str) -> checks.Error:
51
+ return checks.Error(
52
+ f"Model {model} inherits from AutoValidateModelMixin but places it "
53
+ f"AFTER the model base class in its MRO. The mixin's save() is "
54
+ f"bypassed; move the mixin before the model base.",
55
+ id="validation_lifecycle.E004",
56
+ )
57
+
58
+
59
+ def _e005(value) -> checks.Error:
60
+ return checks.Error(
61
+ f"VALIDATION_LIFECYCLE['ASYNC_RULES_BEHAVIOR'] must be one of "
62
+ f"'skip', 'warn', or 'raise'; got {value!r}.",
63
+ id="validation_lifecycle.E005",
64
+ )
65
+
66
+
67
+ def _e006(key: str, expected: str, got_type: str) -> checks.Error:
68
+ return checks.Error(
69
+ f"VALIDATION_LIFECYCLE['{key}'] must be {expected}; got {got_type}.",
70
+ id="validation_lifecycle.E006",
71
+ )
72
+
73
+
74
+ def _e007(model: str) -> checks.Error:
75
+ return checks.Error(
76
+ f"Model {model} defines `async def clean()`. Django's full_clean() "
77
+ f"calls clean() synchronously — the coroutine is never awaited and the "
78
+ f"body never runs. Use a `@validate` rule (sync or async) instead.",
79
+ id="validation_lifecycle.E007",
80
+ )
81
+
82
+
83
+ def _e008(model: str, field: str) -> checks.Error:
84
+ return checks.Error(
85
+ f"Model {model} defines `async def clean_{field}()`. Django's "
86
+ f"clean_fields() calls it synchronously — the coroutine is never "
87
+ f"awaited. Use a sync clean_{field}() or a `@validate` rule instead.",
88
+ id="validation_lifecycle.E008",
89
+ )
90
+
91
+
92
+ def _e009(got_type: str) -> checks.Error:
93
+ return checks.Error(
94
+ f"VALIDATION_LIFECYCLE must be a dict; got {got_type}.",
95
+ id="validation_lifecycle.E009",
96
+ )
97
+
98
+
99
+ def _w001(key: str, valid: list[str]) -> checks.Warning:
100
+ return checks.Warning(
101
+ f"VALIDATION_LIFECYCLE contains unknown key {key!r}. "
102
+ f"Valid keys: {valid}.",
103
+ id="validation_lifecycle.W001",
104
+ )
105
+
106
+
107
+ # ---------------------------------------------------------------------------
108
+ # Helpers
109
+ # ---------------------------------------------------------------------------
110
+ def _iter_effective_rules(model):
111
+ """Collect rules defined on ``model``, its plain mixins, and its abstract
112
+ ancestors. Concrete parents are skipped — their rules get validated when
113
+ ``apps.get_models()`` iterates them.
114
+
115
+ Honors ``@no_validate`` (removal sentinel).
116
+ """
117
+ rules_by_name: dict[str, ValidateRule] = {}
118
+ for base in reversed(model.__mro__):
119
+ if base is not model:
120
+ meta = getattr(base, "_meta", None)
121
+ if meta is not None and not meta.abstract:
122
+ # Concrete parent — its rules are checked on its own iteration.
123
+ continue
124
+ for name, attr in vars(base).items():
125
+ rule = getattr(attr, _VALIDATE_ATTR, None)
126
+ if rule is None:
127
+ continue
128
+ if rule is _VALIDATE_REMOVED:
129
+ rules_by_name.pop(name, None)
130
+ else:
131
+ rules_by_name[name] = rule
132
+ return rules_by_name
133
+
134
+
135
+ def _check_field_refs(model, method_name, rule):
136
+ errors = []
137
+ refs = list(rule.fields)
138
+ if rule.when:
139
+ refs.append(rule.when)
140
+ for field_name in refs:
141
+ try:
142
+ model._meta.get_field(field_name)
143
+ except Exception:
144
+ errors.append(_e002(model._meta.label, method_name, field_name))
145
+ return errors
146
+
147
+
148
+ # ---------------------------------------------------------------------------
149
+ # Checks
150
+ # ---------------------------------------------------------------------------
151
+ @checks.register(checks.Tags.models)
152
+ def check_validate_rules(app_configs=None, **kwargs):
153
+ """E001 (rules without mixin) and E002 (invalid field refs)."""
154
+ if not vl_settings.SYSTEM_CHECKS:
155
+ return []
156
+
157
+ errors = []
158
+ for model in apps.get_models():
159
+ rules = _iter_effective_rules(model)
160
+ if not rules:
161
+ continue
162
+ if not issubclass(model, ValidationModelMixin):
163
+ errors.append(_e001(model._meta.label))
164
+ continue
165
+ for name, rule in rules.items():
166
+ errors.extend(_check_field_refs(model, name, rule))
167
+ return errors
168
+
169
+
170
+ @checks.register(checks.Tags.models)
171
+ def check_mixin_order(app_configs=None, **kwargs):
172
+ """E003 / E004 — mixin placed after the model base in MRO."""
173
+ if not vl_settings.SYSTEM_CHECKS:
174
+ return []
175
+
176
+ errors = []
177
+ for model in apps.get_models():
178
+ if not issubclass(model, ValidationModelMixin):
179
+ continue
180
+
181
+ # Identity comparison is precise: only flags the exact case where
182
+ # Django's own implementation wins the MRO race. If the user overrides
183
+ # full_clean/save themselves, they take responsibility and we don't
184
+ # false-positive.
185
+ if model.full_clean is models.Model.full_clean:
186
+ errors.append(_e003(model._meta.label))
187
+ continue
188
+
189
+ if (
190
+ issubclass(model, AutoValidateModelMixin)
191
+ and model.save is models.Model.save
192
+ ):
193
+ errors.append(_e004(model._meta.label))
194
+ return errors
195
+
196
+
197
+ @checks.register(checks.Tags.models)
198
+ def check_async_clean(app_configs=None, **kwargs):
199
+ """E007 / E008 — async clean() / clean_<field>() silently no-op."""
200
+ if not vl_settings.SYSTEM_CHECKS:
201
+ return []
202
+
203
+ errors = []
204
+ for model in apps.get_models():
205
+ if inspect.iscoroutinefunction(model.clean):
206
+ errors.append(_e007(model._meta.label))
207
+
208
+ seen = {"clean"} # avoid double-checking the base name
209
+ for base in reversed(model.__mro__):
210
+ for name in vars(base):
211
+ if not name.startswith("clean_") or name in seen:
212
+ continue
213
+ seen.add(name)
214
+ method = getattr(model, name, None)
215
+ if method is not None and inspect.iscoroutinefunction(method):
216
+ errors.append(
217
+ _e008(model._meta.label, name[len("clean_"):]),
218
+ )
219
+ return errors
220
+
221
+
222
+ @checks.register() # no tags — settings check runs regardless of DB tag
223
+ def check_settings(app_configs=None, **kwargs):
224
+ """E005 / E006 / E009 / W001 — VALIDATION_LIFECYCLE sanity.
225
+
226
+ Deliberately not gated on SYSTEM_CHECKS — a typo'd setting is exactly the
227
+ case where the user should still get feedback.
228
+ """
229
+ errors = []
230
+
231
+ user_settings = vl_settings.user_settings
232
+ if not isinstance(user_settings, dict):
233
+ return [_e009(type(user_settings).__name__)]
234
+
235
+ if not isinstance(vl_settings.AUTO_VALIDATE_ON_SAVE, bool):
236
+ errors.append(
237
+ _e006(
238
+ "AUTO_VALIDATE_ON_SAVE",
239
+ "a bool",
240
+ type(vl_settings.AUTO_VALIDATE_ON_SAVE).__name__,
241
+ ),
242
+ )
243
+ if not isinstance(vl_settings.SYSTEM_CHECKS, bool):
244
+ errors.append(
245
+ _e006(
246
+ "SYSTEM_CHECKS",
247
+ "a bool",
248
+ type(vl_settings.SYSTEM_CHECKS).__name__,
249
+ ),
250
+ )
251
+
252
+ behaviour = vl_settings.ASYNC_RULES_BEHAVIOR
253
+ if behaviour not in ("skip", "warn", "raise"):
254
+ errors.append(_e005(behaviour))
255
+
256
+ for key in user_settings:
257
+ if key not in DEFAULTS:
258
+ errors.append(_w001(key, sorted(DEFAULTS.keys())))
259
+
260
+ return errors
@@ -0,0 +1,47 @@
1
+ """Settings for validation_lifecycle.
2
+
3
+ Users configure via ``settings.VALIDATION_LIFECYCLE``::
4
+
5
+ VALIDATION_LIFECYCLE = {
6
+ "AUTO_VALIDATE_ON_SAVE": True,
7
+ "SYSTEM_CHECKS": True,
8
+ "ASYNC_RULES_BEHAVIOR": "warn",
9
+ }
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Any
15
+
16
+ from django.conf import settings
17
+
18
+ DEFAULTS: dict[str, Any] = {
19
+ # Whether AutoValidateModelMixin calls full_clean() in save().
20
+ "AUTO_VALIDATE_ON_SAVE": True,
21
+ # Whether to run system checks at startup.
22
+ "SYSTEM_CHECKS": True,
23
+ # What full_clean() (sync) does when async rules exist on the model:
24
+ # "skip" — silently skip async rules
25
+ # "warn" — log a warning and skip (default)
26
+ # "raise" — raise RuntimeError (strict mode)
27
+ "ASYNC_RULES_BEHAVIOR": "warn",
28
+ }
29
+
30
+
31
+ class ValidationLifecycleSettings:
32
+ """Lazy settings reader — respects ``override_settings`` in tests."""
33
+
34
+ def __init__(self, defaults: dict[str, Any] | None = None) -> None:
35
+ self.defaults = {**DEFAULTS, **(defaults or {})}
36
+
37
+ @property
38
+ def user_settings(self) -> dict[str, Any]:
39
+ return getattr(settings, "VALIDATION_LIFECYCLE", {}) or {}
40
+
41
+ def __getattr__(self, attr: str) -> Any:
42
+ if attr not in self.defaults:
43
+ raise AttributeError(f"Invalid ValidationLifecycle setting: {attr!r}")
44
+ return self.user_settings.get(attr, self.defaults[attr])
45
+
46
+
47
+ vl_settings = ValidationLifecycleSettings()
File without changes
@@ -0,0 +1,21 @@
1
+ """Friendly createsuperuser wrapper.
2
+
3
+ To use, create ``accounts/management/commands/createsuperuser.py``::
4
+
5
+ from validation_lifecycle.contrib.createsuperuser import Command
6
+ """
7
+
8
+ from django.contrib.auth.management.commands import createsuperuser
9
+ from django.core.exceptions import ValidationError
10
+ from django.core.management.base import CommandError
11
+
12
+
13
+ class Command(createsuperuser.Command):
14
+ """Wraps Django's createsuperuser to convert ValidationError to CommandError."""
15
+
16
+ def handle(self, *args, **options):
17
+ try:
18
+ return super().handle(*args, **options)
19
+ except ValidationError as exc:
20
+ messages = exc.message_dict or {"__all__": exc.messages}
21
+ raise CommandError(f"Invalid user data: {messages}") from exc
@@ -0,0 +1,108 @@
1
+ """Decorators for declarative validation rules."""
2
+
3
+ import inspect
4
+ from collections.abc import Callable
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+ _VALIDATE_ATTR = "_vl_validate_rule"
9
+
10
+ _VALIDATE_REMOVED = object()
11
+
12
+ _UNSET = object()
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class ValidateRule:
17
+ """Metadata attached to a validation method."""
18
+
19
+ method_name: str
20
+ fields: tuple[str, ...] = ()
21
+ order: int = 0
22
+ has_changed: bool = False
23
+ when: str | None = None
24
+ was: Any = _UNSET
25
+ is_now: Any = _UNSET
26
+ skip_if_blank: bool = False
27
+ is_async: bool = False
28
+
29
+
30
+ def validate(
31
+ *fields: str,
32
+ order: int = 0,
33
+ has_changed: bool = False,
34
+ when: str | None = None,
35
+ was: Any = _UNSET,
36
+ is_now: Any = _UNSET,
37
+ skip_if_blank: bool = False,
38
+ ) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
39
+ """Mark a method as a validation rule.
40
+
41
+ If the decorated function is ``async def``, the rule is automatically
42
+ treated as async. Async rules run only in ``afull_clean()`` / ``asave()``;
43
+ sync ``full_clean()`` skips them per ``VALIDATION_LIFECYCLE["ASYNC_RULES_BEHAVIOR"]``.
44
+
45
+ Args:
46
+ *fields: Fields to attach errors to.
47
+ order: Lower runs first.
48
+ has_changed: Run only when at least one of ``fields`` changed
49
+ (new instances always run).
50
+ when: Watch this field for a transition.
51
+ was: Run only if the ``when`` field's previous value equals this.
52
+ is_now: Run only if the ``when`` field's current value equals this.
53
+ skip_if_blank: Skip when any of ``fields`` is ``None`` or ``""``.
54
+ """
55
+ if has_changed and not fields:
56
+ raise TypeError("@validate(has_changed=True) requires at least one field.")
57
+ if when is None and (was is not _UNSET or is_now is not _UNSET):
58
+ raise TypeError("`was` and `is_now` require `when=`.")
59
+ if when is not None and has_changed:
60
+ raise TypeError(
61
+ "@validate: `has_changed` and `when` are mutually exclusive. "
62
+ "`when` already implies the field changed.",
63
+ )
64
+ if when is not None and not fields:
65
+ fields = (when,)
66
+ if skip_if_blank and not fields:
67
+ raise TypeError(
68
+ "@validate(skip_if_blank=True) requires at least one field.",
69
+ )
70
+
71
+ def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
72
+ setattr(
73
+ func,
74
+ _VALIDATE_ATTR,
75
+ ValidateRule(
76
+ method_name=func.__name__,
77
+ fields=fields,
78
+ order=order,
79
+ has_changed=has_changed,
80
+ when=when,
81
+ was=was,
82
+ is_now=is_now,
83
+ skip_if_blank=skip_if_blank,
84
+ is_async=inspect.iscoroutinefunction(func),
85
+ ),
86
+ )
87
+ return func
88
+
89
+ return decorator
90
+
91
+
92
+
93
+ def no_validate(func):
94
+ """Remove any ``@validate`` rule inherited from a parent class.
95
+
96
+ Apply to a method that overrides a parent's decorated rule to remove
97
+ the rule entirely from the subclass (and its descendants, unless they
98
+ re-decorate with ``@validate``).
99
+
100
+ Example::
101
+
102
+ class Tenant(CustomUser):
103
+ @no_validate
104
+ def username_validate(self):
105
+ return
106
+ """
107
+ setattr(func, _VALIDATE_ATTR, _VALIDATE_REMOVED)
108
+ return func
File without changes
File without changes
@@ -0,0 +1,98 @@
1
+ """Audit existing rows against your current @validate rules.
2
+
3
+ Usage:
4
+ python manage.py vl_check # all models
5
+ python manage.py vl_check accounts.CustomUser # one model
6
+ python manage.py vl_check --limit=10 # stop after 10 failures
7
+ """
8
+
9
+ from __future__ import annotations
10
+ import asyncio
11
+ from django.core.checks import run_checks
12
+ from django.core.exceptions import ValidationError
13
+ from django.core.management.base import BaseCommand, CommandError
14
+
15
+ from validation_lifecycle.mixins import ValidationModelMixin
16
+ from django.apps import apps
17
+
18
+ class Command(BaseCommand):
19
+ help = "Run full_clean() over existing rows and report validation failures."
20
+
21
+ def add_arguments(self, parser):
22
+ parser.add_argument(
23
+ "model",
24
+ nargs="?",
25
+ help="Specific model label (app_label.ModelName). Default: all.",
26
+ )
27
+ parser.add_argument(
28
+ "--limit",
29
+ type=int,
30
+ default=0,
31
+ help="Stop after N failures (0 = unlimited).",
32
+ )
33
+
34
+ def handle(self, *args, **options):
35
+ # Run system checks first (if the app is installed).
36
+ if "validation_lifecycle" in [c.name for c in apps.get_app_configs()]:
37
+ check_errors = [
38
+ e for e in run_checks() if e.id.startswith("validation_lifecycle.")
39
+ ]
40
+ if check_errors:
41
+ for err in check_errors:
42
+ self.stderr.write(self.style.ERROR(f"[{err.id}] {err.msg}"))
43
+ raise CommandError("Fix configuration errors first.")
44
+
45
+ if options["model"]:
46
+ try:
47
+ model = apps.get_model(options["model"])
48
+ except LookupError as exc:
49
+ raise CommandError(str(exc)) from exc
50
+ if not issubclass(model, ValidationModelMixin):
51
+ raise CommandError(
52
+ f"{model._meta.label} does not inherit from ValidationModelMixin.",
53
+ )
54
+ models = [model]
55
+ else:
56
+ models = [
57
+ m for m in apps.get_models() if issubclass(m, ValidationModelMixin)
58
+ ]
59
+
60
+ total, failures, limit = 0, 0, options["limit"]
61
+ with asyncio.Runner() as runner:
62
+
63
+ for model in models:
64
+ self.stdout.write(self.style.MIGRATE_HEADING(f"→ {model._meta.label}"))
65
+ has_async = bool(model._vl_get_async_rules())
66
+
67
+ for instance in model.objects.all().iterator():
68
+ total += 1
69
+
70
+ try:
71
+ if has_async:
72
+ runner.run(instance.afull_clean())
73
+
74
+ else:
75
+ instance.full_clean()
76
+
77
+ except ValidationError as exc:
78
+ failures += 1
79
+
80
+ pk = instance.pk
81
+
82
+ self.stdout.write(
83
+
84
+ self.style.ERROR(f" ✗ pk={pk}: {exc.message_dict}"))
85
+
86
+ if limit and failures >= limit:
87
+ self.stdout.write(self.style.WARNING("Reached --limit; stopping."))
88
+ return None
89
+
90
+ self.stdout.write(self.style.SUCCESS(f" ✓ {model._meta.label} done"))
91
+
92
+ summary = f"{total} rows checked, {failures} failures"
93
+
94
+ if failures:
95
+ self.stdout.write(self.style.ERROR(summary))
96
+
97
+ else:
98
+ self.stdout.write(self.style.SUCCESS(summary))
File without changes
@@ -0,0 +1,369 @@
1
+ """Mixins that wire @validate rules into Django's validation lifecycle."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from typing import Any
7
+
8
+ from asgiref.sync import sync_to_async
9
+ from django.core.exceptions import ValidationError
10
+
11
+ from .conf import vl_settings
12
+ from .decorators import _UNSET, ValidateRule
13
+ from .registry import collect_rules
14
+
15
+ logger = logging.getLogger("validation_lifecycle")
16
+
17
+
18
+ def _normalize(exc: ValidationError, fields: tuple[str, ...]) -> ValidationError:
19
+ """Map a plain ValidationError to the rule's declared fields."""
20
+ if hasattr(exc, "error_dict"):
21
+ return exc
22
+ if fields:
23
+ return ValidationError(dict.fromkeys(fields, exc.messages))
24
+ return exc
25
+
26
+
27
+ def _extract_exclude(args: tuple, kwargs: dict) -> set[str]:
28
+ """Read ``exclude`` from full_clean's positional or keyword arguments."""
29
+ exclude = kwargs.get("exclude")
30
+ if exclude is None and args:
31
+ exclude = args[0]
32
+ return set(exclude or ())
33
+
34
+
35
+
36
+ class ValidationModelMixin:
37
+ """Runs @validate methods inside full_clean() / afull_clean()."""
38
+
39
+ _vl_rules_cache: list[ValidateRule] | None = None
40
+ _vl_sync_rules_cache: list[ValidateRule] | None = None
41
+ _vl_async_rules_cache: list[ValidateRule] | None = None
42
+ _vl_initial: dict[str, Any] | None = None
43
+
44
+ # ------------------------------------------------------------------
45
+ # Rule discovery
46
+ # ------------------------------------------------------------------
47
+ @classmethod
48
+ def _vl_get_rules(cls) -> list[ValidateRule]:
49
+ if (
50
+ "_vl_rules_cache" not in cls.__dict__
51
+ or cls.__dict__["_vl_rules_cache"] is None
52
+ ):
53
+ cls._vl_rules_cache = collect_rules(cls)
54
+ return cls._vl_rules_cache
55
+
56
+ @classmethod
57
+ def _vl_get_sync_rules(cls) -> list[ValidateRule]:
58
+ if (
59
+ "_vl_sync_rules_cache" not in cls.__dict__
60
+ or cls.__dict__["_vl_sync_rules_cache"] is None
61
+ ):
62
+ cls._vl_sync_rules_cache = [
63
+ r for r in cls._vl_get_rules() if not r.is_async
64
+ ]
65
+ return cls._vl_sync_rules_cache
66
+
67
+ @classmethod
68
+ def _vl_get_async_rules(cls) -> list[ValidateRule]:
69
+ if (
70
+ "_vl_async_rules_cache" not in cls.__dict__
71
+ or cls.__dict__["_vl_async_rules_cache"] is None
72
+ ):
73
+ cls._vl_async_rules_cache = [r for r in cls._vl_get_rules() if r.is_async]
74
+ return cls._vl_async_rules_cache
75
+
76
+ def _vl_refresh_initial(self, update_fields: list[str] | None) -> None:
77
+ """Advance the change-tracking snapshot after a successful save.
78
+
79
+ If ``update_fields`` was given, only advance it for those fields —
80
+ the rest of the instance may diverge from the DB and must keep their
81
+ pre-save snapshot values so ``has_changed`` stays truthful.
82
+ """
83
+ if update_fields is None or self._vl_initial is None:
84
+ self._vl_initial = self._vl_snapshot()
85
+ return
86
+
87
+ attname_to_name = {
88
+ f.attname: f.name for f in self._meta.concrete_fields if f.attname != f.name
89
+ }
90
+
91
+ written = {attname_to_name.get(f, f) for f in update_fields}
92
+
93
+ for f in self._meta.concrete_fields:
94
+ if f.name in written:
95
+ self._vl_initial[f.name] = getattr(self, f.attname)
96
+
97
+ def _vl_presave_auto_fields(self) -> None:
98
+ """Populate auto_now / auto_now_add on new instances before validation.
99
+
100
+ Django sets these inside ``save_base`` (via ``Field.pre_save``), which
101
+ runs *after* ``full_clean()``. Without this, rules on new instances see
102
+ ``None`` for those fields.
103
+
104
+ On updates we deliberately don't fire ``pre_save`` for ``auto_now``
105
+ fields — doing so would make them look "changed" to ``has_changed``
106
+ rules even though the user didn't modify anything.
107
+ """
108
+ if not self._state.adding:
109
+ return
110
+
111
+ for f in self._meta.concrete_fields:
112
+ if getattr(f, "auto_now", False) or getattr(f, "auto_now_add", False):
113
+ f.pre_save(self, add=True)
114
+
115
+ # ------------------------------------------------------------------
116
+ # Initial snapshot
117
+ # ------------------------------------------------------------------
118
+ def __init__(self, *args, **kwargs) -> None:
119
+ super().__init__(*args, **kwargs)
120
+ self._vl_initial = self._vl_snapshot()
121
+
122
+ def _vl_snapshot(self) -> dict[str, Any]:
123
+ # Skip deferred fields — accessing them would trigger a DB query.
124
+ deferred = self.get_deferred_fields()
125
+ return {
126
+ f.name: getattr(self, f.attname)
127
+ for f in self._meta.concrete_fields
128
+ if f.attname not in deferred
129
+ }
130
+
131
+ def refresh_from_db(self, *args, **kwargs) -> None:
132
+ super().refresh_from_db(*args, **kwargs)
133
+ self._vl_initial = self._vl_snapshot()
134
+
135
+ def _vl_has_changed(self, field_name: str) -> bool:
136
+ if self._vl_initial is None or field_name not in self._vl_initial:
137
+ return True
138
+ return getattr(self, field_name) != self._vl_initial[field_name]
139
+
140
+ def _vl_is_blank(self, field_name: str) -> bool:
141
+ try:
142
+ value = getattr(self, field_name)
143
+ except AttributeError:
144
+ return False
145
+ return value is None or value == ""
146
+
147
+ def _vl_exclude_from_update_fields(self, update_fields: list[str]) -> set[str]:
148
+ """Compute full_clean's ``exclude`` from save()'s ``update_fields``.
149
+
150
+ Translates FK attnames (``customer_id``) to field names (``customer``)
151
+ so rules on the FK aren't silently skipped.
152
+ """
153
+ attname_to_name = {
154
+ f.attname: f.name for f in self._meta.concrete_fields if f.attname != f.name
155
+ }
156
+ written = {attname_to_name.get(f, f) for f in update_fields}
157
+ all_fields = {f.name for f in self._meta.concrete_fields}
158
+ return all_fields - written
159
+
160
+ # ------------------------------------------------------------------
161
+ # Decision: should this rule run?
162
+ # ------------------------------------------------------------------
163
+ def _vl_should_run(self, rule: ValidateRule) -> bool:
164
+ if rule.skip_if_blank and rule.fields:
165
+ if any(self._vl_is_blank(f) for f in rule.fields):
166
+ return False
167
+
168
+ if rule.when is not None:
169
+ return self._vl_check_when(rule)
170
+
171
+ if not rule.has_changed:
172
+ return True
173
+ if self._state.adding:
174
+ return True
175
+ return any(self._vl_has_changed(f) for f in rule.fields)
176
+
177
+ def _vl_check_when(self, rule: ValidateRule) -> bool:
178
+ when_field = rule.when
179
+
180
+ if rule.is_now is not _UNSET:
181
+ if getattr(self, when_field) != rule.is_now:
182
+ return False
183
+
184
+ # Do we have a prior state to compare against?
185
+ # False on create, OR when the field was deferred and never loaded.
186
+ has_prior = (
187
+ not self._state.adding
188
+ and self._vl_initial is not None
189
+ and when_field in self._vl_initial
190
+ )
191
+
192
+ if not has_prior:
193
+ # `was` cannot match — no prior state to compare against.
194
+ if rule.was is not _UNSET:
195
+ return False
196
+ return True
197
+
198
+ if not self._vl_has_changed(when_field):
199
+ return False
200
+
201
+ if rule.was is not _UNSET:
202
+ if self._vl_initial[when_field] != rule.was:
203
+ return False
204
+
205
+ return True
206
+
207
+ # ------------------------------------------------------------------
208
+ # Sync execution
209
+ # ------------------------------------------------------------------
210
+ def run_validations(self, exclude: set[str] | None = None) -> None:
211
+ """Run sync rules and aggregate their errors."""
212
+ exclude = exclude or set()
213
+ errors: dict[str, list[str]] = {}
214
+ for rule in self._vl_get_sync_rules():
215
+ if exclude and rule.fields and any(f in exclude for f in rule.fields):
216
+ continue
217
+ if not self._vl_should_run(rule):
218
+ continue
219
+ method = getattr(self, rule.method_name)
220
+ try:
221
+ method()
222
+ except ValidationError as exc:
223
+ errors = _normalize(exc, rule.fields).update_error_dict(errors)
224
+ if errors:
225
+ raise ValidationError(errors)
226
+
227
+ # ------------------------------------------------------------------
228
+ # Async execution
229
+ # ------------------------------------------------------------------
230
+ async def arun_validations(self, exclude: set[str] | None = None) -> None:
231
+ """Run async rules and aggregate their errors."""
232
+ exclude = exclude or set()
233
+ errors: dict[str, list[str]] = {}
234
+ for rule in self._vl_get_async_rules():
235
+ if exclude and rule.fields and any(f in exclude for f in rule.fields):
236
+ continue
237
+ if not self._vl_should_run(rule):
238
+ continue
239
+ method = getattr(self, rule.method_name)
240
+ try:
241
+ await method()
242
+ except ValidationError as exc:
243
+ errors = _normalize(exc, rule.fields).update_error_dict(errors)
244
+ if errors:
245
+ raise ValidationError(errors)
246
+
247
+ # ------------------------------------------------------------------
248
+ # Sync entry point
249
+ # ------------------------------------------------------------------
250
+ def full_clean(self, *args, **kwargs) -> None:
251
+ self._vl_presave_auto_fields()
252
+ exclude_set = _extract_exclude(args, kwargs)
253
+
254
+ # If async rules exist, apply the configured behaviour.
255
+ async_rules = self._vl_get_async_rules()
256
+ if async_rules:
257
+ behaviour = vl_settings.ASYNC_RULES_BEHAVIOR
258
+ if behaviour == "raise":
259
+ raise RuntimeError(
260
+ f"{self.__class__.__name__} has async validation rules "
261
+ f"but full_clean() is sync. Use `await instance.afull_clean()` "
262
+ f"instead, or set VALIDATION_LIFECYCLE['ASYNC_RULES_BEHAVIOR'] "
263
+ f"to 'warn' or 'skip'.",
264
+ )
265
+ if behaviour == "warn":
266
+ logger.warning(
267
+ "%s.full_clean(): skipping async rule(s) %s — "
268
+ "call `await instance.afull_clean()` for full validation.",
269
+ self.__class__.__name__,
270
+ [r.method_name for r in async_rules],
271
+ )
272
+ # "skip" falls through silently.
273
+
274
+ errors: dict[str, list[str]] = {}
275
+
276
+ try:
277
+ super().full_clean(*args, **kwargs)
278
+ except ValidationError as exc:
279
+ errors = exc.update_error_dict(errors)
280
+ if hasattr(exc, "error_dict"):
281
+ exclude_set |= set(exc.error_dict.keys())
282
+
283
+ try:
284
+ self.run_validations(exclude=exclude_set)
285
+ except ValidationError as exc:
286
+ errors = exc.update_error_dict(errors)
287
+
288
+ if errors:
289
+ raise ValidationError(errors)
290
+
291
+ # ------------------------------------------------------------------
292
+ # Async entry point
293
+ # ------------------------------------------------------------------
294
+ async def afull_clean(self, *args, **kwargs) -> None:
295
+ """Async version of full_clean() — runs sync and async rules."""
296
+ self._vl_presave_auto_fields()
297
+
298
+ exclude_set = _extract_exclude(args, kwargs)
299
+
300
+ errors: dict[str, list[str]] = {}
301
+
302
+ # 1. Django's standard validation. `Model.full_clean` isn't async-safe
303
+ # (validate_unique hits the DB), so run it through sync_to_async.
304
+ # `super()` here skips our own sync override, so rules don't run
305
+ # twice.
306
+ try:
307
+ await sync_to_async(super().full_clean)(*args, **kwargs)
308
+ except ValidationError as exc:
309
+ errors = exc.update_error_dict(errors)
310
+
311
+ if hasattr(exc, "error_dict"):
312
+ exclude_set |= set(exc.error_dict.keys())
313
+
314
+ # 2. Sync @validate rules — via sync_to_async so rule bodies that
315
+ # touch the ORM run in Django's sync-safe thread pool.
316
+ try:
317
+ await sync_to_async(self.run_validations)(exclude=exclude_set)
318
+ except ValidationError as exc:
319
+ errors = exc.update_error_dict(errors)
320
+
321
+
322
+ # 3. Async @validate rules
323
+ try:
324
+ await self.arun_validations(exclude=exclude_set)
325
+ except ValidationError as exc:
326
+ errors = exc.update_error_dict(errors)
327
+
328
+ if errors:
329
+ raise ValidationError(errors)
330
+
331
+
332
+ class AutoValidateModelMixin(ValidationModelMixin):
333
+ """Adds save()-time validation on top of ValidationModelMixin.
334
+
335
+ Sync path: save() → full_clean() (async rules skipped per setting).
336
+ Async path: await asave() → afull_clean() (all rules run).
337
+ """
338
+
339
+ def save(self, *args, **kwargs):
340
+ update_fields = kwargs.get("update_fields")
341
+ if vl_settings.AUTO_VALIDATE_ON_SAVE:
342
+ if update_fields is not None:
343
+ exclude = self._vl_exclude_from_update_fields(update_fields)
344
+ self.full_clean(exclude=exclude or None)
345
+ else:
346
+ self.full_clean()
347
+
348
+ result = super().save(*args, **kwargs)
349
+
350
+ self._vl_refresh_initial(update_fields)
351
+
352
+ return result
353
+
354
+ async def asave(self, *args, **kwargs):
355
+ """Async save that runs async validation rules before writing."""
356
+ update_fields = kwargs.get("update_fields")
357
+
358
+ if vl_settings.AUTO_VALIDATE_ON_SAVE:
359
+ if update_fields is not None:
360
+ exclude = self._vl_exclude_from_update_fields(update_fields)
361
+ await self.afull_clean(exclude=exclude or None)
362
+ else:
363
+ await self.afull_clean()
364
+
365
+ result = await sync_to_async(super().save)(*args, **kwargs)
366
+
367
+ self._vl_refresh_initial(update_fields)
368
+
369
+ return result
@@ -0,0 +1,37 @@
1
+ """Rule discovery and caching."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ from .decorators import _VALIDATE_ATTR, _VALIDATE_REMOVED, ValidateRule
8
+
9
+ if TYPE_CHECKING:
10
+ from django.db.models import Model
11
+
12
+
13
+ def collect_rules(cls: type[Model]) -> list[ValidateRule]:
14
+ """Collect @validate rules from a model class and its bases.
15
+
16
+ Walks MRO base→derived so subclasses override parents, then sorts by
17
+ ``(order, method_name)`` for deterministic execution. A method decorated
18
+ with ``@no_validate`` removes any inherited rule of the same name.
19
+ """
20
+ rules_by_name: dict[str, ValidateRule] = {}
21
+
22
+ for base in reversed(cls.__mro__):
23
+
24
+ for name, attr in base.__dict__.items():
25
+
26
+ rule = getattr(attr, _VALIDATE_ATTR, None)
27
+
28
+ if rule is None:
29
+ continue
30
+
31
+ if rule is _VALIDATE_REMOVED:
32
+ rules_by_name.pop(name, None)
33
+
34
+ else:
35
+ rules_by_name[name] = rule
36
+
37
+ return sorted(rules_by_name.values(), key=lambda r: (r.order, r.method_name))