Skip to content

Add BEFORE_CLEAN / AFTER_CLEAN hooks to support validation events #171

@konradbeck-creditech

Description

@konradbeck-creditech

Description:
Allow django-lifecycle to register hooks around model validation by firing new events when Model.full_clean() or clean() runs.

Motivation:

  • Validation in clean() today must be wired by hand, losing override benefits of lifecycle hooks.
  • Form/Admin calls full_clean() under the hood—it’d be valuable to have BEFORE_CLEAN/AFTER_CLEAN events so errors integrate seamlessly with Django’s validation pipeline.

Proposal:

  1. Define two new events (BEFORE_CLEAN, AFTER_CLEAN) in the priority module.
  2. Wrap Model.full_clean() (or inside Model.clean()) to run those hooks before/after validation:
def full_clean(self, *args, **kwargs):
    self._run_hooks(BEFORE_CLEAN)
    super().full_clean(*args, **kwargs)
    self._run_hooks(AFTER_CLEAN)
  1. Update docs to show how to use @hook(BEFORE_CLEAN) and @hook(AFTER_CLEAN) for modular validation.
@hook(BEFORE_CLEAN)
def normalize_phone(self):
    self.phone = clean_number(self.phone)

@hook(AFTER_CLEAN)
def check_business_rules(self):
    if self.quantity < 0:
        raise ValidationError({"quantity": "must be positive"})

Happy to help iterate on details or a PR!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions