pythondjangodjango-signalsdjango-emaildjango-messages

How to get currently logged-in user in signals.py file?


I'm making a todo app and one of it's functionalities is to send an email to the user that his task was overdue.

Part of the views.py file:

from .models import Todo
from django.utils import timezone
from .signals import overdue

def index(request):
    ...
    overdue_tasks = Todo.objects.filter(time__lte=timezone.now())
    if overdue_tasks:
        overdue.send_robust(sender=Todo)
    ...
    return render(request, 'todo/index.html', {'overdue_tasks' : overdue_tasks })

Part of the signals.py file:

from django.dispatch import receiver, Signal
from .models import Todo
from django.core.mail import send_mail

overdue = Signal()
user_email = request.user.email

@receiver(overdue)
def my_handler(sender, **kwargs):
    send_mail('Subject', 'Your task was Overdue !', 'myemail@gmail.com', 'user_email', fail_silently=False)'

It's raising exception:

"NameError: name 'request isn't defined."


Solution

  • You are tryng to acess te request trough request.user.email without a request to acess, you can acess the user email on index view, pass the email as a **kwarg and acess on my_handler

    def index(request):
        ...
        overdue_tasks = Todo.objects.filter(time__lte=timezone.now())
        if overdue_tasks:
            overdue.send_robust(sender=Todo, email=request.user.email)
        ...
        return render(request, 'todo/index.html', {'overdue_tasks' : overdue_tasks })
    
    @receiver(overdue)
    def my_handler(sender, **kwargs):
        email = kwargs.get('email')
        send_mail(foo)