0

I'm using Celery in a Django project and I'm trying to get the current user in file tasks.py. I don't want to use "User.objects.get(id)" because I can't pass an argument (id) to the function. Is there something similar to "request.user" that I can use?

Thanks a lot.

Bruniik
  • 21
  • 4
  • A task has no user, or at least not a user like a request. A task can run onder an OS user, but that is a different set of users. – Willem Van Onsem Aug 07 '19 at 10:09
  • So there is no way to get the user without using User.objects.get? – Bruniik Aug 07 '19 at 11:02
  • @Biniik: even `User.objects.get(..)` will not retrieve anything. What `id` would you pass? There is no "current user" in a task that is triggered through a management command/celery. – Willem Van Onsem Aug 07 '19 at 11:03
  • Yes, you are right. Well, if I use task.delay() in some view I could pass the id of the user logged in. But it's not the idea that I have. Anyway, thank you ;) – Bruniik Aug 07 '19 at 11:16

1 Answers1

0

Look at the following post and scroll down to the answer. Just use the middleware in your task instead of a signal. I am doing this for user notifications where the task speaks to the WebSocket group defined by the user pk on a post_save signal:

Post:

Accessing the user's request in a post_save signal

Answer:

You can do that with the help of middleware. Create get_request.py in your app. Then

JessicaRyan
  • 115
  • 3
  • 14