Getting User Object from Username in Django

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.

1

2 Answers

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)
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest