I am trying the following code in a django celery task
@app.task
def search(q, userstring):
uid = User.objects.get(username=userstring)
messages.info(uid, 'Initiating search in background.')
[...]
My view is calling it as follows:
search.delay(self.request.user.get_username(), form.instance.query)
I am getting the following error:
>[2014-06-05 12:04:04,352: ERROR/MainProcess] Task listthings.tasks.search[5aaa77b4-c7be-4d6a-9127-626e63d0dfbe] raised unexpected: DoesNotExist('User matching query does not >exist.',)
Traceback (most recent call last):
File "/webapps/wcw/local/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task
R = retval = fun(*args, **kwargs)
File "/webapps/wcw/local/lib/python2.7/site-packages/celery/app/trace.py", line 437, in __protected_call__
return self.run(*args, **kwargs)
__File "/webapps/wcw/webcamwatch/listcams/tasks.py", line 44, in search
uid = User.objects.get(username=userstring)__
File "/webapps/wcw/local/lib/python2.7/site-packages/django/db/models/manager.py", line 151, in get
return self.get_queryset().get(*args, **kwargs)
File "/webapps/wcw/local/lib/python2.7/site-packages/django/db/models/query.py", line 310, in get
self.model._meta.object_name)
Exception: User matching query does not exist.
What I am trying to achieve is to pass the active user from the view into django-aync-messages
Any recommendations or pointers to my error (including a better way!) gratefully appreciated.
There's nothing wrong with the way you're querying for the user. The problem with your code is that you have passed the variables in the wrong order: the task is expecting (q, userstring)
but you are passing (username, query)
.
However I wonder why you are querying on username at all when you could simply pass the primary key of the User instance:
def search(q, user_id):
uid = User.objects.get(pk=user_id)
and call it:
search.delay(form.instance.query, self.request.user.pk)
You need to handle the case when there is no user in some way for example:
@app.task
def search(q, userstring):
try:
uid = User.objects.get(username=userstring)
except DoesNotExist, e:
return None
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With