Como já indicaram, o request já contem o logged user. Contudo, quando tens de utilizar para vários objetos, eu utilizo uma class abstract, e aqui defino o atributos que são sempre iguais, ou seja, quem criou e quando, quem atualizou e quando e reutilizo esta as vezes que quiser.
Contudo, implica instalar um package, podes fazer assim:
pip install ai-django-core
E defines o middleware assim:
settings.py
MIDDLEWARE = (
...
'django.contrib.auth.middleware.AuthenticationMiddleware',
'ai.middleware.current_user.CurrentUserMiddleware',
)
Começas por adicionar um ficheiro common.py:
common.py
from django.conf import settings
from django.db import models
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from ai.middleware.current_user import CurrentUserMiddleware
from django.contrib.contenttypes.fields import GenericRelation
class CommonInfo(models.Model):
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_("Created By"), blank=True, null=True, related_name="%(app_label)s_%(class)s_created", on_delete=models.SET_NULL, editable=False)
created_on = models.DateTimeField(auto_now_add=True, blank=True, null=True, editable=False)
modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_("Modified By"), blank=True, null=True, related_name="%(app_label)s_%(class)s_modified_on", on_delete=models.SET_NULL)
modified_on = models.DateTimeField(auto_now=True, blank=True, null=True)
@staticmethod
def get_current_user():
"""
Get the currently logged in user over middleware.
Can be overwritten to use e.g. other middleware or additional functionality.
:return: user instance
"""
return CurrentUserMiddleware.get_current_user()
def set_user_fields(self, user):
"""
Set user-related fields before saving the instance.
If no user with primary key is given the fields are not set.
:param user: user instance of current user
"""
if user and user.pk:
if not self.pk:
self.created_by = user
else:
self.modified_by = user
def save(self, *args, **kwargs):
self.modified_on = now()
current_user = self.get_current_user()
self.set_user_fields(current_user)
super(CommonInfo, self).save(*args, **kwargs)
class Meta:
abstract = True
models.py
from myapp.common import CommonInfo
class Inscricao(CommonInfo): # <= tens de adicionar aqui o CommonInfo ao invés do models.Model
pessoa = models.ForeignKey(User, verbose_name='usuario', on_delete=models.CASCADE)
evento = models.ForeignKey(Evento, verbose_name='evento', on_delete=models.CASCADE)
categoria = models.ForeignKey(Categoria, verbose_name='categoria', on_delete=models.CASCADE)
numero = models.IntegerField(verbose_name='número', blank=True)
data_inscricao = models.DateField(verbose_name='data de inscrição', blank=True)
detalhe = models.TextField(max_length=100, verbose_name='observação', blank=True)
Inscricao
recebe umrequest
. Nesse request você pega os dados necessário (ex:request.user
para usuário logado) e instancia seu Model com os dados corretos.