'Django - Is there any way to get the current logged user in the signals.py file of my proyect?
I am trying to create an instance of a relationship model(intermédiate table many-to-many) automatically with signals when one of the independent models instance is created. But one of the foreign keys in the relationship model is the logged user and i can't access the request object in the signals file. maybe there is another without signals but idk. Any suggestions are appreciated. UserAccount is a custom user model. this is the code
models.py
from datetime import datetime
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from apps.accounts.models import UserAccount
class Patient(models.Model):
name = models.CharField(max_length=50)
userAccount = models.ManyToManyField('accounts.UserAccount', through='Therapy')
class Therapy(models.Model):
patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
userAccount = models.ForeignKey(UserAccount, on_delete=models.CASCADE)
createdDate = models.DateTimeField(auto_now_add=True)
signals.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Patient, Therapy
@receiver(post_save, sender=Patient)
def create_therapy(sender, instance, created, **kwargs):
if created:
Therapy.objects.create(patient=instance, userAccount=request.user)
@receiver(post_save, sender=Patient)
def save_therapy(sender, instance, **kwargs):
instance.patient.save()
Solution 1:[1]
Try with:
import getpass
current_logged_in_user = getpass.getuser()
you have to install getpass before, in your command line run:
pip install getpass4
Solution 2:[2]
This worked for me:
if created:
import inspect
request = None
for fr in inspect.stack():
if fr[3] == 'get_response':
request = fr[0].f_locals['request']
break
current_logged_in_user = request.user
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | richardec |