43 lines
1.1 KiB
Python
43 lines
1.1 KiB
Python
from django.db import models
|
|
from django.contrib.auth import get_user_model
|
|
from core.middleware.current_request import get_current_user
|
|
|
|
|
|
UserModel = get_user_model()
|
|
|
|
|
|
class BaseModel(models.Model):
|
|
"""Abstract base model that includes created_by and updated_by fields.
|
|
|
|
The fields are automatically populated with the current user from the request.
|
|
"""
|
|
|
|
created_by = models.ForeignKey(
|
|
UserModel,
|
|
on_delete=models.SET_NULL,
|
|
null=True,
|
|
blank=True,
|
|
related_name="%(class)s_created",
|
|
editable=False,
|
|
)
|
|
updated_by = models.ForeignKey(
|
|
UserModel,
|
|
on_delete=models.SET_NULL,
|
|
null=True,
|
|
blank=True,
|
|
related_name="%(class)s_updated",
|
|
editable=False,
|
|
)
|
|
created_at = models.DateTimeField(auto_now_add=True)
|
|
updated_at = models.DateTimeField(auto_now=True)
|
|
|
|
class Meta:
|
|
abstract = True
|
|
|
|
def save(self, *args, **kwargs):
|
|
current_user = get_current_user()
|
|
if not self.pk and not self.created_by:
|
|
self.created_by = current_user
|
|
self.updated_by = current_user
|
|
super().save(*args, **kwargs)
|