如何在 signals.py 文件中获取当前登录的用户?
How to get currently logged-in user in signals.py file?
我正在制作一个 todo 应用程序,其中一个功能是 向 的用户发送一封电子邮件 ]他的任务逾期了。
views.py 文件的一部分:
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 })
signals.py 文件的一部分:
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)'
引发异常:
"NameError: name 'request isn't defined."
您正在尝试通过 request.user.email
访问请求而不请求访问,您可以在 index
查看时访问用户电子邮件,将电子邮件作为 **kwarg 传递并在 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)
我正在制作一个 todo 应用程序,其中一个功能是 向 的用户发送一封电子邮件 ]他的任务逾期了。
views.py 文件的一部分:
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 })
signals.py 文件的一部分:
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)'
引发异常:
"NameError: name 'request isn't defined."
您正在尝试通过 request.user.email
访问请求而不请求访问,您可以在 index
查看时访问用户电子邮件,将电子邮件作为 **kwarg 传递并在 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)