LexModel Internals
LexModel is the base class for every data model in Lex App. It extends django-lifecycle's LifecycleModel with automatic history tracking, permission hooks, validation hooks, and Streamlit integration.
Browse the full source on GitHub.
from lex.core.models.LexModel import LexModel, UserContext, PermissionResultAuto-Provided Fields
Every LexModel subclass automatically gets these fields — you never need to declare them:
Field | Type | Description |
|---|---|---|
|
| Primary key (inherited from Django) |
|
| Username of the creator (set automatically) |
|
| Username of the last editor (set automatically for normal user edits; calculation-triggered framework saves don't overwrite it) |
History fields (via django-simple-history) are added transparently — you don't interact with them directly.
Lifecycle Hooks
pre_validation(self)
Called before every save (create or update). Raise any exception to cancel the save — the record will not be written to the database.
def pre_validation(self):
if self.amount <= 0:
raise ValueError("Amount must be positive.")post_validation(self)
Called after the save completes. Raise any exception to trigger an automatic rollback — the framework restores the record to its pre-save state.
def post_validation(self):
if self.team.budget - self.amount < 0:
raise ValueError("This would exceed the team budget.")Both hooks are wired via django-lifecycle's
@hook(BEFORE_SAVE)and@hook(AFTER_SAVE)decorators internally. You just override the method — no decorator needed on your side.
Permission Methods
Lex App checks permissions automatically on every API request and frontend interaction. Override these methods on your model to customize access control.
Field-Level Methods (return PermissionResult)
Method | Default Behavior | When It's Called |
|---|---|---|
| Allow if Keycloak | Every GET / list request |
| Allow if Keycloak | Every PATCH / PUT request |
| Allow if Keycloak | CSV / Excel export |
These return a PermissionResult which can grant access to all fields, specific fields, or deny access entirely.
Action-Level Methods (return bool)
Method | Default Behavior | When It's Called |
|---|---|---|
| Allow if Keycloak | POST request |
| Allow if Keycloak | DELETE request |
| Allow if Keycloak | List / table view |
UserContext
A frozen dataclass passed to every permission method. It contains everything you need to make authorization decisions.
@dataclass(frozen=True)
class UserContext:
user: Any # Django User instance
email: str
is_authenticated: bool
is_superuser: bool
groups: Set[str] # Keycloak / Django groups
keycloak_scopes: Set[str] # Keycloak UMA scopes for this resource
user_permissions: tuple[...] # Raw Keycloak UMA permissions
client_roles: FrozenSet[str] # Keycloak client rolesConstructed automatically from the Django request via UserContext.from_request(request, instance).
PermissionResult
A frozen dataclass returned by field-level permission methods. Use the factory methods:
Factory | What It Does |
|---|---|
| Grant access to every field |
| Grant access to specific fields only |
| Grant access to all fields except listed ones |
| Deny access entirely |
| Explicit alias for |
Convenience Helpers
LexModel includes helper methods you can call inside your permission methods to reduce boilerplate:
def permission_read(self, user_context):
# Check superuser first
result = self.allow_all_if_superuser(user_context)
if result:
return result
# Check group membership
result = self.allow_all_if_in_groups(user_context, {"admin", "manager"})
if result:
return result
# Check record ownership
result = self.allow_fields_if_owner(
user_context,
owner_field="created_by",
excluded_fields={"internal_notes"},
)
if result:
return result
# Fall back to Keycloak
return self.keycloak_fallback(user_context, "read")Helper | Returns |
|---|---|
|
|
|
|
| Grants access if the user owns the record |
| Falls back to Keycloak scope check |
| Excludes common sensitive fields ( |
Streamlit Methods
Method | Level | Description |
|---|---|---|
| Record-level | Override for per-record Streamlit dashboard |
| Table-level ( | Override for model-wide dashboard |
Always import
streamlitinside these methods, not at the top of the file. See Part 5 — Streamlit Dashboards for details.
History Tracking Control
Method | What It Does |
|---|---|
| Re-enable history tracking for this instance |
| Disable history tracking for the next save |
| Save once without creating a history entry |
For bulk operations where history tracking is expensive, use Model.objects.bulk_create(objs, skip_history=True).
Was this helpful?
Your feedback shapes what we write next.
